引用到這個問題: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