在C#中,我可以从T转换为at T:new()

在C#中,我可以从T转换为at T:new(),c#,generics,C#,Generics,这是我的密码: void DoSomething<T>() { var constructor = typeof(T).GetConstructor(null); if(constructor != null) { DoSomethingElse<T>(); // compiler error } else { //... } } void DoSomethingElse&

这是我的密码:

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();
   //...
}
void DoSomething()
{
var constructor=typeof(T).GetConstructor(null);
if(构造函数!=null)
{
DoSomethingElse();//编译器错误
}
其他的
{
//...   
}
}
void DoSomethingElse(),其中T:new()
{
T x=新的T();
//...
}

有没有办法让编译器相信T是合法的T:new()?

除了添加
new()
约束之外,没有办法让编译器相信T,如果你做不到这一点,唯一的办法就是使用
反射

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); 

除了添加一个
new()

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); 

嗯,不。显然,编译器不是这样工作的:)您还需要向第一个方法添加
new()
约束。不能。DoSomething需要处理所有类型,而不仅仅是那些具有默认构造函数的类型。嗯,然后你可以尝试使用反射调用
DoSomethingElse
。这对你有帮助吗:这里还有一篇帖子:嗯,没有。显然,编译器不是这样工作的:)你还需要向第一个方法添加
new()
约束。不行。DoSomething需要处理所有类型,而不仅仅是具有默认构造函数的类型。嗯,然后您可以尝试使用反射调用
DoSomethingElse
。这对您有帮助吗:还有以下帖子: