[英]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.