C#泛型方法,在新的()构造函数约束类型参数 [英] C# generic methods, type parameters in new() constructor constraint

查看:598
本文介绍了C#泛型方法,在新的()构造函数约束类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来创建一个使用新()构造函数约束,要求使用特定类型的构造函数的类的一般方法?

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.

我使用通用的参数构造的解决方法是指定的构造为代表:

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

这篇关于C#泛型方法,在新的()构造函数约束类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆