2012-06-02 108 views
0

我有這樣的類和接口:C#鑄造泛型類型,以正確的類型

public class XContainer 
{ 
    public List<IXAttribute> Attributes { get; set; } 
} 

public interface IXAttribute 
{ 
    string Name { get; set; } 
} 

public interface IXAttribute<T> : IXAttribute 
{ 
    T Value { get; set; } 
} 

public class XAttribute<T> : IXAttribute<T> 
{ 
    public T Value { get; set; } 
} 

我需要遍歷XContainer.Attributes並獲得財產Value但我需要投IXAttribute糾正像XAttribute<string>XAttribute<int>但我通用表示不想使用if-else if-else語句來檢查它是否就像XContainerl.Attributes[0] is XAttribute<string>然後投射...

這裏是更好的方法嗎?

回答

1

有一個更好的方法來做到這一點。

假設你保持目前的整體設計,你可以改變你的非通用接口和實現如下:

public interface IXAttribute 
{ 
    string Name { get; set; } 
    object GetValue(); 
} 

public class XAttribute<T> : IXAttribute<T> 
{ 
    public T Value { get; set; } 

    public object GetValue() 
    { 
     return Value; 
    } 
} 

然後你的迭代器將只訪問GetValue(),沒有必要鑄造。

這就是說,我認爲設計可能不是你所做的最好的。

+0

謝謝你的回答。你建議更好的設計? – Simon

+0

也許泛型不適合這個。但是我們必須看到更多的實際代碼。 –

0

你也可以定義一個通用的擴展方法

public static class XAttributeExtensions 
{ 
    public T GetValueOrDefault<T>(this IXAttribute attr) 
    {   
     var typedAttr = attr as IXAttribute<T>; 
     if (typedAttr == null) { 
      return default(T); 
     } 
     return typedAttr.Value; 
    } 
} 

然後你可以調用它(假設Tint

int value = myAttr.GetValueOrDefault<int>(); 

之所以實現它作爲一個擴展方法,它將與非通用接口IXAttribute的任何實現一起工作。