C# 可为空的泛型声明?
假设我有一个目标C# 可为空的泛型声明?,c#,.net,generics,.net-3.5,types,C#,.net,Generics,.net 3.5,Types,假设我有一个目标 Class A<T, T2> { public T MyObject {get;set;} public IList<A<T2>> MyChildren {get;set;} } A类 { 公共T MyObject{get;set;} 公共IList MyChildren{get;set;} } 问题是,有时我没有孩子,所以我不想声明孩子类型aka T2,知道吗?我不能像这样通过 A a = new A<string,
Class A<T, T2>
{
public T MyObject {get;set;}
public IList<A<T2>> MyChildren {get;set;}
}
A类
{
公共T MyObject{get;set;}
公共IList MyChildren{get;set;}
}
问题是,有时我没有孩子,所以我不想声明孩子类型aka T2,知道吗?我不能像这样通过
A a = new A<string, Nullable>(); as it is throwing an error.
A A=新A();因为它正在抛出一个错误。
感谢无法为泛型类型参数指定“null”-如果在类中声明它们,则在使用该类时它们是必需的 如果您仔细想想,这是有道理的,因为如果没有
T2
,您的类将部分未定义,这是机器无法很好地处理的
你可能需要做的是把你的班级一分为二。首先,你们班没有孩子:
class Widget<T>
{
public T MyObject { get; set; }
}
class WidgetWithChildren<T,T2>: Widget<T>
{
public IList<Widget<T>> MyChildren { get; set; }
}
类小部件
{
公共T MyObject{get;set;}
}
然后,添加了对儿童的支持的扩展:
class Widget<T>
{
public T MyObject { get; set; }
}
class WidgetWithChildren<T,T2>: Widget<T>
{
public IList<Widget<T>> MyChildren { get; set; }
}
类WidgetWithChildren:Widget
{
公共IList MyChildren{get;set;}
}
不过,这只是一个部分解决方案,因为你没有办法处理孙子辈。Nullable是一个通用的it本身,所以你必须做一些类似的事情
new A<string, Nullable<?>>();
newa