你想要什麼不是直接支持在C#中。因爲Constraints on Type參數只能在構造函數,繼承層次結構,接口實現等幾個方面得到滿足。 more details
,你可以用不同的方式做到這一點,但是在這種方法中,沒有編譯時錯誤:
公共接口IMyConstraint { 無效DO(); }
public class MyClass: IMyConstraint
{
public void Do()
{
}
}
// Inherit from the List class to add some functionality to it
public class MyTypeList<T> : List<T> where T : System.Type
{
public MyTypeList()
{
}
// use new keyword to prevent client from using the List.Add method.
public new void Add(T type)
{
// here you check if the type is implementing the interface or not
if (!typeof(IMyConstraint).IsAssignableFrom(type))
{
// if it dose not implement the interface just throw an exception
throw new InvalidOperationException();
}
// call the original List.Add method
base.Add(type);
}
}
來源
2015-10-04 14:48:19
SHM
默認(A [1])將始終返回'null',你需要更好地詳細說明用例。 –
'default(Type t)'必須返回使用默認無參構造函數創建的對象(如果存在)。在我的情況下'Type t'可以是'typeof(MyClass1..3)'。 –
什麼只應該接受類型,爲什麼?你想做什麼? –