我正在尝试编写一个通用方法来获取 XElement
强类型时尚的值(value)。这是我拥有的:
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);
}
}
}
正如您在 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.");
}
我在 GetElementValue<int>
时得到以下异常被称为:
System.InvalidCastException : Cannot cast element value '5' to type 'Int32'.
我是否必须分别处理每个转换案例(或至少是数字案例)?
最佳答案
您也可以试试 Convert.ChangeType
Convert.ChangeType(element.Value, typeof(TElementType))
关于c# - 如何转换为 C# 中的泛型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3881140/