我只是有這個簡單的泛型類,它應該取T並創建一個屬性。如果我嘗試獲取此屬性並且它不存在,它應該創建此T類型的新實例並將其返回。這就是爲什麼我需要在T上設置新的()約束。帶默認構造函數的通用對象列表
public class ExternalRepository<T> where T : class, IRepositoryable, new()
{
public IRepositoryable Value
{
get
{
if (RequestCacheManager.GetAt<T>(typeof(T).Name) == null)
RequestCacheManager.SetAt<T>(typeof(T).Name, new T());
return RequestCacheManager.GetAt<T>(typeof(T).Name);
}
}
}
現在我需要創建這些列表。但由於new()約束,它看起來像是不可能的。我需要這樣的東西:
public static List<ExternalRepository<T>> ExternalRepositories { get; set; } where T : class, IRepositoryable, new()
但這是無效的。你能幫我解決這個問題嗎?
謝謝。
你不能創建通用屬性,所以你不能爲它設置約束?嘗試使用'method'而不是'property'就像'public static List> ExternalRepositories ()其中T:class,IRepositoryable,new()' –
Grundy
我需要創建屬性。方法很好,但它只是在方法內部移動這個問題。 –
所以在這種情況下,你可以使泛型類包含這個屬性併爲它設置約束條件 – Grundy