[英]Type conversion mismatch with generic extension method
I am attempting to hide a whole set of legacy methods behind a single extension method using generics. 我正在尝试使用泛型在单个扩展方法后面隐藏整套旧方法。 These legacy methods are all called GetValidXXX and have a similar signature (and yes they should really be out not ref ).
这些传统方法都称为GetValidXXX并且具有类似的签名(是的,他们确实应该出不REF)。 The old GetValidXXX need to be kept for backwards compatibility.
为了向后兼容,需要保留旧的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;
}
This will not compile because result does not match the type in the specific GetValidXXX signature (return values is success/fail). 由于结果与特定GetValidXXX签名中的类型不匹配(返回值为成功/失败),因此不会编译。
bool GetValidAttribute(DbAttribute attribute, ref DbAttribute result)
bool GetValidBool(DbAttribute attribute, ref bool result)
etc
How can I write this to achieve what I am aiming for ie to be able to write code that looks like this: 我该如何编写代码以实现我的目标,即能够编写如下代码:
string description = element.GetAttributeValue(DbAttributeInstance.DESC, "unset");
bool isWritable = !element.GetAttributeValue(DbAttributeInstance.READONLY, true);
You can't use T
for your ref parameters because the compiler cannot always guarantee it will be of those types. 您不能将
T
用于您的ref参数,因为编译器无法始终保证它属于那些类型。 You would have to do something like this: 您将必须执行以下操作:
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()
might be useful in your case. Convert.ChangeType()
在您的情况下可能很有用。
Possible usage: 可能的用法:
public static T ConvertTypeOrGetDefault<T>(this object value, T defaultValue)
{
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (Exception ex)
{
return default(T);
}
}
It depends on how "hacky" you're willing to be. 这取决于您愿意成为什么样的“ hacky”。 You also could consider re-factoring so that you don't have to hide the legacy methods.
您还可以考虑进行重构,这样就不必隐藏传统方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.