引用到这个问题:Cannot create an instance of the variable type 'Item' because it does not have the new() constraint初始化泛型类型非空的构造
我想从一个普通型与非空的构造函数创建一个实例。
public class A{};
public class B
{
public B(int){/*...*/}
}
public class C
{
public static T validate<T>(int index)
where T : A,
new(int) //error
{
if(/*validation*/)
return null;
return new T(index);
}
}
如果我尝试致电B b = validate<B>(42);
我得到这个错误:
'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C.validate(int)'
问题1:为什么我只能用一个参数构造函数?
问题2:如何解决我的问题,无需委托或接口? (我一直在寻找奇特的解决方案。)
问题1的答案很简单:[它尚未构建](https://github.com/dotnet/roslyn/issues/2206)。这不是C#的限制; CLR本身不支持这些限制,需要扩展才能实现。它不是那些令人敬畏的功能,也不是那些令人敬畏的功能之一。(对于初学者,想象一下'new(int,int,bool,int,bool)' - 它可能符合你的一种形式构造函数,但好运算出构造函数应该*做*。) –
一个简单的解决方法是使用'new()'约束并使用默认构造函数(添加它)。然后使用'Index'属性:'public static T validate(int index) 其中T:A,new() if(validation) return null; T t = new T(); t.Index = index; return t; }'否则你可以使用'Activator.CreateInstance'就像[here](https://stackoverflow.com/a/15003163/284240) –
好消息 - 他们不想构建它。看到这篇文章:https://github.com/dotnet/csharplang/issues/769。这篇文章还包含一个可能的解决方案/解决方法。 – Mafii