具有泛型类型参数的对象初始值设定项

时间:2014-03-26 18:15:45

标签: c# generics

如何使用传入的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;
    }

1 个答案:

答案 0 :(得分:4)

您应该使用包含所需属性的基类:

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;
}