c# - 如何转换为 C# 中的泛型参数?

标签 c# generics casting linq-to-xml xelement

我正在尝试编写一个通用方法来获取 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/

相关文章:

转换 void 指针并使用格式说明符打印

c# - 在 C# 中将对象 T 转换为 List<T>

c# - 检查类是否已实例化

c# - 将 .well-known 添加到 asp.net core

java - 泛型的类型安全

ios - 具有关联类型要求和默认实现的 Swift 协议(protocol)

c# - 如何将列号(例如 127)转换为 Excel 列(例如 AA)

c# - WPF 中的 CommandLink

c# - 对嵌套的通用列表进行排序/排序

python 列表类型转换和设置值