C# 泛型方法,new() 构造函数约束中的类型参数

C# 泛型方法,new() 构造函数约束中的类型参数

问题描述:

有没有办法创建一个通用方法,它使用 new() 构造函数约束来要求具有特定类型构造函数的类?

Is there a way to create a Generic Method that uses the new() constructor constraint to require classes with constructors of specific types?

例如:

我有以下代码:

public T MyGenericMethod<T>(MyClass c) where T : class
{
    if (typeof(T).GetConstructor(new Type[] { typeof(MyClass) }) == null)
    {
        throw new ArgumentException("Invalid class supplied");
    }
    // ...
}

有没有可能有这样的东西?

Is it possible to have something like this instead?

public T MyGenericMethod<T>(MyClass c) where T : new(MyClass)
{
    // ...
}

关于此的建议.请投票,以便我们可以在 C# 中使用此功能!


There's a suggestion regarding this. Please vote so we can have this feature in C#!

不是真的;C# 仅支持无参数构造函数约束.

Not really; C# only supports no-args constructor constraints.

我用于泛型 arg 构造函数的解决方法是将构造函数指定为委托:

The workaround I use for generic arg constructors is to specify the constructor as a delegate:

public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) {
    // ...
    T newTObj = ctor(c);
    // ...
}

然后在调用时:

MyClass c = new MyClass();
MyGenericMethod<OtherClass>(c, co => new OtherClass(co));