2008-09-12 65 views
2

我面臨着.NET泛型的一個問題。我想要做的事情是節省泛型類型(GraphicsItem)數組:在數組中保存一個開放的泛型類型?

public class GraphicsItem<T> 
{ 
    private T _item; 

    public void Load(T item) 
    { 
     _item = item; 
    } 
} 

我如何在一個數組保存這樣的開放式泛型類型?

回答

4

實現非通用接口和使用:

public class GraphicsItem<T> : IGraphicsItem 
{ 
    private T _item; 

    public void Load(T item) 
    { 
     _item = item; 
    } 

    public void SomethingWhichIsNotGeneric(int i) 
    { 
     // Code goes here... 
    } 
} 

public interface IGraphicsItem 
{ 
    void SomethingWhichIsNotGeneric(int i); 
} 

然後使用該接口在列表中的項目:

var values = new List<IGraphicsItem>(); 
0

如果要存儲異構GrpahicsItem的即GraphicsItem < X>和GrpahicsItem < Y>您需要從公共基類派生它們或實現通用接口。另一種選擇是將它們存儲在列表中<對象>

0

您是否嘗試在非泛型方法中創建GraphicsItem數組?

你不能做到以下幾點:

static void foo() 
{ 
    var _bar = List<GraphicsItem<T>>(); 
} 

再後來填充列表。

更可能你正在嘗試做這樣的事情?

static GraphicsItem<T>[] CreateArrays<T>() 
{ 
    GraphicsItem<T>[] _foo = new GraphicsItem<T>[1]; 

    // This can't work, because you don't know if T == typeof(string) 
    // _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>(); 

    // You can only create an array of the scoped type parameter T 
    _foo[0] = new GraphicsItem<T>(); 

    List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>(); 

    // Again same reason as above 
    // _bar.Add(new GraphicsItem<string>()); 

    // This works 
    _bar.Add(new GraphicsItem<T>()); 

    return _bar.ToArray(); 
} 

請記住,您將需要一個泛型類型引用來創建一個泛型類型的數組。這可以在方法級別(在方法之後使用T)或在類級別(在課程之後使用T)。

如果您希望該方法返回一個GraphicsItem和GraphicsItem數組,然後讓GraphicsItem繼承一個非泛型基類GraphicsItem並返回一個數組。雖然你會失去所有類型的安全。

希望有所幫助。