[英]C# Casting generics type to right type
我有這個類和接口:
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>
則XContainerl.Attributes[0] is XAttribute<string>
...
這是更好的方法嗎?
有更好的方法可以做到這一點。
假設您希望保留當前的總體設計,則可以如下更改非通用接口和實現:
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()
,而無需強制轉換。
就是說,我認為設計可能不是您正在做的最好的設計。
您還可以定義通用擴展方法
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;
}
}
然后可以用調用它(假定T
為int
)
int value = myAttr.GetValueOrDefault<int>();
將其實現為擴展方法的原因是,它將與非通用接口IXAttribute
任何實現IXAttribute
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.