我正在尝试编写一个以强类型方式获取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的第一个尝试行中看到的那样,我正试图从字符串 – >对象 – > 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 : Cannot cast element value ‘5’ to type ‘Int32’.
我是否必须分别处理每个铸造案例(或至少是数字案例)?
解决方法
你也可以试试
Convert.ChangeType
Convert.ChangeType(element.Value,typeof(TElementType))