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