我有以下内容:
GenericClass<T> : Class
{
T Results {get; protected set;}
public GenericClass<T> (T results, Int32 id) : base (id)
{
Results=results;
}
public static GenericClass<T> Something (Int32 id)
{
return new GenericClass<T> (i need to pass something like new T?, id);
}
}
Update T 可以是类型也可以是值,因此使用 new() 对某些类型是可以的,但对值肯定不行。我想这意味着一些类的重新设计。
想法是如何使用构造函数?例如,是否可以传递类似于 new T 的东西(尽管它不应该,因为当时 T 还不知道)或者要避免传递 null 会有什么变化?
最佳答案
这应该有效:
GenericClass<T> : Class where T : new()
{
T Results {get; protected set;}
public GenericClass<T> (T results, Int32 id)
{
Results=results;
}
public GenericClass<T> Something (Int32 id) : this(new T(), id)
{ }
}
关于c# - C# 中的泛型构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390526/