[英]Generic method to instantiate a variable of any type (including nullable struct)?
假设我有此函数,该函数实例化任何类型的默认/空值的new
变量
public static T GetDefault<T>() where T : new() //body of this method is the question
{
T t = new T();
return t;
}
上面的函数的问题是当我有类似int?
东西int?
对于T
因为如果我有
int? t = new int?();
t
将为空! 我不希望这种情况发生,而是希望返回int
的默认值0
。
为了解决这个问题,我可以为int?
有不同的GetDefault
函数重载int?
, bool?
等,但这并不优雅。 我也可以在函数内部检查类型是否为int?
还是bool?
等等,但是我将如何实例化它的基类型呢?
或者问题归结为如何识别T
是否为可为空的结构,以及相应地如何实例化可为空的结构。
Type realType = Nullable.GetUnderlyingType(typeof(T));
t = (T)Activator.CreateInstance(realType ?? typeof(T));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.