[英]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.