在C#中,我可以从一个T转换为at T:new()
本文关键字:一个 转换 new at 我可以 | 更新日期: 2024-09-23 17:23:38
这是我的代码:
void DoSomething<T>()
{
var constructor = typeof(T).GetConstructor(null);
if(constructor != null)
{
DoSomethingElse<T>(); // compiler error
}
else
{
//...
}
}
void DoSomethingElse<T>() where T:new()
{
T x = new T();
//...
}
有没有办法让编译器相信T是合法的T:new()?
除了添加new()
约束之外,没有其他方法可以说服编译器,如果不能做到这一点,唯一的方法就是使用Reflection
:
var methodType = // get the type of DoSomethingElse here
var genericMethod = methodType.MakeGenericMethod(typeof(T));
// pass instance instead of null if this is an instance method
genericMethod.Invoke(null);