[英]Inherit from a class that has a generic type
我有一個具有通用類型的類
class GenericClass<T> where T : new()
{
public T GenericType;
public GenericClass()
{
GenericType = new T();
}
}
現在,我想創建從GenericClass繼承但將新類作為類型傳遞的新類。
所以...
class Class1:GenericClass<Class1>
{
public string Class1Property { get; set; }
}
class Class2 : GenericClass<Class2>
{
public string Class2Property { get; set; }
}
如果執行此操作,然后創建Class 1的新實例,則代碼將陷入無限循環。
Class1 c1 = new Class1();
我想做的事可能嗎?
的線
GenericType = new T();
在您的基本構造函數中,將為繼承類型調用構造函數,后者將調用基本構造函數,后者將繼續循環。
如果您只是想跟蹤繼承的類的類型,請嘗試
typeof(T);
要么
this.GetType();
當他們獲得類型時,無需創建該類型的新實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.