2014-02-28 55 views
0

我只是有這個簡單的泛型類,它應該取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() 

但這是無效的。你能幫我解決這個問題嗎?

謝謝。

+0

你不能創建通用屬性,所以你不能爲它設置約束?嘗試使用'method'而不是'property'就像'public static List > ExternalRepositories ()其中T:class,IRepositoryable,new()' – Grundy

+0

我需要創建屬性。方法很好,但它只是在方法內部移動這個問題。 –

+0

所以在這種情況下,你可以使泛型類包含這個屬性併爲它設置約束條件 – Grundy

回答

1

你想把ExternalRepository<Person>ExternalRepository<Order>放在一個列表中,是否正確?

不幸的是,這不能明確做到。你將不得不使用接口或基類。

public interface IExternalRepository 
{ 
    // declaration of common properties and methods 
} 

public class ExternalRepository<T> : IExternalRepository 
    where T : class, IRepositoryable, new() 
{ 
    // implementation of common properties and methods 
    // own properties and methods 
} 

public static List<IExternalRepository> ExternalRepositories { get; set; } 

public class ExternalRepository 
{ 
    // shared properties and methods 
} 

public class ExternalRepository<T> : ExternalRepository 
    where T : class, IRepositoryable, new() 
{ 
    // own properties and methods 
} 

public static List<ExternalRepository> ExternalRepositories { get; set; } 

也看到我的答覆this問題。

+0

是的,我也嘗試了List >,但是這會拋出錯誤,因爲T類型必須有隱含的構造函數。這就是爲什麼我需要以某種方式設置列表上的約束。錯誤是這樣的:'ServiceModel.Interface.IRepositoryable'必須是一個具有公共無參數構造函數的非抽象類型,以便將其用作泛型類型或方法'SSO2.Managers.ExternalRepository '中的參數'T'。 –

+0

請參閱編輯回覆澄清。 –

+0

太好了,謝謝。我試圖解決它很長一段時間沒有停頓,我完全忽略了這個解決方案。現在看起來完全明顯:-) –

相關問題