Sco*_*ott 7 c# generics xelement casting linq-to-xml
我正在尝试编写一种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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到First attempt的那样GetElementValue,我试图从字符串 - >对象 - > 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.");
}
Run Code Online (Sandbox Code Playgroud)
GetElementValue<int>调用时我得到以下异常:
System.InvalidCastException:无法将元素值'5'强制转换为'Int32'.
我是否必须分别处理每个铸造案例(或至少是数字案例)?
Pat*_*tko 11
您也可以尝试Convert.ChangeType
Convert.ChangeType(element.Value, typeof(TElementType))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7102 次 |
| 最近记录: |