我正在尝试编写一种通用方法,以强类型方式获取XElement
值。以下是我的代码:
public static class XElementExtensions
{
public static XElement GetElement(this XElement xElement, string elementName)
{
// Calls xElement.Element(elementName) and returns that xElement (with some validation).
}
public static TElementType GetElementValue<TElementType>(this XElement xElement, string elementName)
{
XElement element = GetElement(xElement, elementName);
try
{
return (TElementType)((object) element.Value); // First attempt.
}
catch (InvalidCastException originalException)
{
string exceptionMessage = string.Format("Cannot cast element value '{0}' to type '{1}'.", element.Value,
typeof(TElementType).Name);
throw new InvalidCastException(exceptionMessage, originalException);
}
}
}
正如您在GetElementValue
的First attempt
行中所看到的,我试图从字符串 -> 对象 -> TElementType。不幸的是,这对于整数测试用例不起作用。当运行以下测试时:
[Test]
public void GetElementValueShouldReturnValueOfIntegerElementAsInteger()
{
const int expectedValue = 5;
const string elementName = "intProp";
var xElement = new XElement("name");
var integerElement = new XElement(elementName) { Value = expectedValue.ToString() };
xElement.Add(integerElement);
int value = XElementExtensions.GetElementValue<int>(xElement, elementName);
Assert.AreEqual(expectedValue, value, "Expected integer value was not returned from element.");
}
当调用
GetElementValue<int>
时,我会收到以下异常:
我需要单独处理每个转换情况(或者至少是数字情况)吗?System.InvalidCastException:无法将元素值“5”转换为类型“Int32”。
ChangeType
仍然返回一个对象,但隐式转换现在起作用了。此外,我现在在try/catch
块中检查FormatException
而不是InvalidCastException
。简短明了的回答。 - Doctor Blue