C# generic methods, type parameters in new() constructor constraint

后端 未结 3 970
一整个雨季
一整个雨季 2020-12-01 10:44

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

For

相关标签:
3条回答
  • 2020-12-01 11:22

    No, it is not possible in C# to constrain the generic type to have a constructor of a specific signature. Only the parameterless constructor is supported by new().

    0 讨论(0)
  • 2020-12-01 11:23

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

    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);
        // ...
    }
    

    then when calling:

    MyClass c = new MyClass();
    MyGenericMethod<OtherClass>(c, co => new OtherClass(co));
    
    0 讨论(0)
  • 2020-12-01 11:44

    No. Unfortunately, generic constraints only allow you to include:

    where T : new()
    

    Which specifies that there is a default, parameterless constructor. There is no way to constrain to a type with a constructor which accepts a specific parameter type.

    For details, see Constraints on Type Parameters.

    0 讨论(0)
提交回复
热议问题