【问题标题】:In C# can I cast from a T to at T : new()在 C# 中,我可以从 T 转换到 T :new()
【发布时间】:2016-04-18 15:22:05
【问题描述】:

这是我的代码:

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()?

【问题讨论】:

标签: c# generics


【解决方案1】:

除了添加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); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多