Jun*_* Li 12 c# generics types default
我正在研究C#泛型函数.当出错时,如果泛型类型可以是新的,则返回new T(),否则返回default(T).
像这样的代码:
private T Func<T>()
{
try
{
// try to do something...
}
catch (Exception exception)
{
if (T is new-able) // <---------- How to do this?
{
return new T();
}
else
{
return default(T);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道where T : new()那些使用它的人需要new T().这个问题是,如何在运行时判断这个?
Sri*_*vel 20
您只需要检查该类型是否具有无参数构造函数.您可以通过Type.GetConstructor使用空类型作为参数调用方法来实现.
var constructorInfo = typeof(T).GetConstructor(Type.EmptyTypes);
if(constructorInfo != null)
{
//here you go
object instance = constructorInfo.Invoke(null);
}
Run Code Online (Sandbox Code Playgroud)
如果我没记错的话,Activator.CreateInstance<T>将返回使用无参数构造函数构造的对象(如果T是类或default(T)if T是结构).
您可以在Sriram的答案中使用该技术,首先确保存在无参数构造函数T.