简体   繁体   English

C#泛型方法,在new()构造函数约束中输入参数

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

Is there a way to create a Generic Method that uses the new() constructor constraint to require classes with constructors of specific types? 有没有办法创建一个使用new()构造函数约束的通用方法来要求具有特定类型的构造函数的类?

For Example: 例如:

I have the following code: 我有以下代码:

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

EDIT: 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. C#仅支持no-args构造函数约束。

The workaround I use for generic arg constructors is to specify the constructor as a delegate: 我用于通用arg构造函数的解决方法是将构造函数指定为委托:

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

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 . 有关详细信息,请参阅类型参数的约束

No, it is not possible in C# to constrain the generic type to have a constructor of a specific signature. 不,在C#中不可能将泛型类型约束为具有特定签名的构造函数。 Only the parameterless constructor is supported by new(). new()仅支持无参数构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有新类型约束的泛型构造函数 - Generic constructor with new type constraint C# 泛型类型约束取决于使用的构造函数 - C# generic type constraint depending on used constructor C#是具有通用类型约束的通用类型 - C# is generic type with generic type constraint C#泛型问题 - 使用构造函数中的参数新建泛型类型 - C# generics problem - newing up the generic type with parameters in the constructor 在C#7本地方法中重新引入新的通用参数是否是一种好习惯? - Is it a good practice to reintroduce new generic parameters in C# 7 Local Methods? C# 中是否有带参数约束的泛型构造函数? - Is there a generic constructor with parameter constraint in C#? C#泛型方法,可以从泛型类型的类型定义中推断参数的类型吗? - C# generic methods, possible to infer type for parameters from generic type's type definition? 通用约束:强制类型具有静态函数和带参数的构造函数 - Generic constraint: Enforce type to have static function and constructor with parameters C# - 具有通用参数的构造函数将这些参数传输到基本构造函数 - C# - Constructor with generic parameters transmitting these parameters to base constructor C#泛型-泛型类型约束 - C# Generics - a generic type constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM