2011-07-18 51 views
2

我不知道如何去這個...非泛型類中的泛型屬性?

我有執行各種功能的類:

public abstract class EntityBase { ... } 

public interface ISomeInterface<T> where T : EntityBase, new() { ... } 

public class SomeClass<T> : ISomeInterface<T> { ... } 

我想有這些高速緩存在非通用類:

public class MyClass 
{ 
    //Not sure how to do this 
    private ConcurrentDictionary<?, ISomeInterface<?>> Cache { get; set; } 
} 

的問題是,EntityBase是抽象的,不能做新的(),該ISomeInterface預計,是基於關閉EntityBase並執行一類新的()。有什麼辦法可以做我想做的事嗎?


更新:我意識到,對於TKEY的,我可以使用Type,但我還是我不知道要放什麼東西了ISomeInterface。

回答

2

首先,我想你打算使用ConcurrentDictionary,因爲你有一個鍵/值對。其次,你可以像ICloneable那樣做。 ICloneable有一個返回Object,而不是一個T.

private ConcurrentDictionary<Type, Object> Cache { get; set; } 

由於它是私有的,你可以在內部進行管理,並根據需要將它轉換的方法。顯然,你必須確保所有的函數調用有typeparam定義,例如:

//I omitted error checking on all the examples. 
public class Foo : EntityBase { ... } 

void DoSomething<Foo>() 
{ 
    var someClass = Cache[typeof(Foo)] as ISomeInterface<Foo> 
    someClass.Bar(); 
} 

而且,即使物業有另外的修飾符(公共的,內部的,受保護的),你可以添加註釋,呼叫者的Object是ISomeInterface的一個通用類型,其中T是一個EntityBase,new()。然後,他們只需投射,但他們需要。


您還可以對非通用類通用的方法來獲取緩存項作爲一個泛型類型:

ISomeInterface<T> GetInstance<T>() 
    where T : EntityBase, new() 
{ 
    return Cache[typeof(T)] as ISomeInterface<T>; 
} 

void AddInstance<T>(ISomeInterface<T> instance) 
    where T : EntityBase, new() 
{ 
    Cache[typeof(T)] = instance; 
} 

void DoSomething<T>() 
{ 
    var someClass = GetInstance<T>(); 
    someClass.Bar(); 
} 
0

請參閱此相關的問題:Making a generic property

如果你不」我希望MyClass是通用的,你可以使用兩種通用的方法來代替:

private ConcurrentCollection<T, ISomeInterface<T>> GetCache<T>() 
    { 
     ... 
    } 

    private void SetCache<T>(ConcurrentCollection<T, ISomeInterface<T>> cache) 
    { 
     ... 
    } 
+0

你將如何實現的方法是什麼? – svick

+0

我想我沒有在我的答案中解決後備存儲問題。 :) –

0

我是不知道究竟你想使用集合,但這樣做類似的東西的一個方法是創建包含值的嵌套泛型靜態類:

class SomeInterfaceCollection 
{ 
    private static class Item<T> 
    { 
     public static ISomeInterface<T> Value; 
    } 

    public static ISomeInterface<T> Get<T>() 
    { 
     return Item<T>.Value; 
    } 

    public static void Set<T>(ISomeInterface<T> value) 
    { 
     Item<T>.Value = value; 
    } 
} 
+0

這隻對靜態屬性有意義。 –

+0

@Ben,你說得對,我已經修復了代碼。 – svick