[英]Type conversion mismatch with generic extension method
我正在嘗試使用泛型在單個擴展方法后面隱藏整套舊方法。 這些傳統方法都稱為GetValidXXX並且具有類似的簽名(是的,他們確實應該出不REF)。 為了向后兼容,需要保留舊的GetValidXXX。
public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue)
{
T result = default(T);
if (typeof(T) == typeof(DbAttribute))
{
if (element.GetValidAttribute(attribute, ref result)) return result;
}
else if (typeof(T) == typeof(bool))
{
if (element.GetValidBool(attribute, ref result)) return result;
}
return defaultValue;
}
由於結果與特定GetValidXXX簽名中的類型不匹配(返回值為成功/失敗),因此不會編譯。
bool GetValidAttribute(DbAttribute attribute, ref DbAttribute result)
bool GetValidBool(DbAttribute attribute, ref bool result)
etc
我該如何編寫代碼以實現我的目標,即能夠編寫如下代碼:
string description = element.GetAttributeValue(DbAttributeInstance.DESC, "unset");
bool isWritable = !element.GetAttributeValue(DbAttributeInstance.READONLY, true);
您不能將T
用於您的ref參數,因為編譯器無法始終保證它屬於那些類型。 您將必須執行以下操作:
public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue)
{
if (typeof(T) == typeof(DbAttribute))
{
var dbAttribute = default(DbAttribute);
if (element.GetValidAttribute(attribute, ref dbAttribute)) return (T)(object)dbAttribute;
}
else if (typeof(T) == typeof(bool))
{
var boolResult = default(bool);
if (element.GetValidBool(attribute, ref boolResult)) return (T)(object)boolResult;
}
return defaultValue;
}
Convert.ChangeType()
在您的情況下可能很有用。
可能的用法:
public static T ConvertTypeOrGetDefault<T>(this object value, T defaultValue)
{
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (Exception ex)
{
return default(T);
}
}
這取決於您願意成為什么樣的“ hacky”。 您還可以考慮進行重構,這樣就不必隱藏傳統方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.