1
这里是我的代码,除了一种情况外,它的工作完美:当我有一个xAttribute
的bool
,所以xAttribute.Value == 1
。在这种情况下,Convert
不适用于数字类型。Generic Cast xAttribute to bool
通常我只会使用output = (bool) xAttribute
,它的工作原理;但在这种方法中,我有一个通用类型,所以我想沿output = (T) xAttribute
行使用该通用类型。我怎样才能做到这一点?
public static bool TryGetValueFromAttribute<T>(
this XElement element,
String attName,
out T output,
T defaultValue)
{
var xAttribute = element.Attribute(attName);
if (xAttribute == null)
{
output = defaultValue;
return false;
}
output = (T)Convert.ChangeType(xAttribute.Value, typeof(T));
return true;
}
的作品,我认为你应该加上`其中T:新的(),class`在函数定义的结束。 – 2011-12-14 10:24:19