相关疑难解决方法(0)

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

有没有办法创建一个使用new()构造函数约束来要求具有特定类型构造函数的类的泛型方法?

例如:

我有以下代码:

public T MyGenericMethod<T>(MyClass c) where T : class
{
    if (typeof(T).GetConstructor(new Type[] { typeof(MyClass) }) == null)
    {
        throw new ArgumentException("Invalid class supplied");
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

是否有可能有这样的东西?

public T MyGenericMethod<T>(MyClass c) where T : new(MyClass)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:一个关于这个的建议.请投票,以便我们可以在C#中使用此功能!

.net c# generics type-constraints

17
推荐指数
2
解决办法
6603
查看次数

标签 统计

.net ×1

c# ×1

generics ×1

type-constraints ×1