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