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

查看:60
本文介绍了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));

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

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