具有泛型类型参数的对象初始化器

本文关键字:初始化 对象 泛型类型参数 | 更新日期: 2023-09-27 17:54:11

如何初始化带有Id参数的T的新对象?

private ICollection<T> AddRelationalData<T>(List<int> relationalDataIds)
        where T : class, new()
    {
        var relationalDataCollection = new Collection<T>()
        if (relationalDataIds != null && relationalDataIds.Count > 0)
        {
            foreach (var entry in relationalDataIds.Select(id => new T {Id = id}))
            {
                relationalDataCollection.Add(entry);
            }
        }
        return relationalDataCollection;
    }

具有泛型类型参数的对象初始化器

您应该使用基类,它包含必需的属性:

public class Test
{
   public int Id {get;set;}
}
private ICollection<T> AddRelationalData<T>(List<int> relationalDataIds)
    where T : Test, new()
{
    var relationalDataCollection = new Collection<T>()
    if (relationalDataIds != null && relationalDataIds.Count > 0)
    {
        foreach (var entry in relationalDataIds.Select(id => new T {Id = id}))
        {
            relationalDataCollection.Add(entry);
        }
    }
    return relationalDataCollection;
}