加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C#中转换为通用参数?

发布时间:2020-12-15 18:23:58 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个以强类型方式获取XElement值的泛型方法.这就是我所拥有的: public static class XElementExtensions{ public static XElement GetElement(this XElement xElement,string elementName) { // Calls xElement.Element(elementName) and ret
我正在尝试编写一个以强类型方式获取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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读