投对象给T [英] Cast object to T

查看:159
本文介绍了投对象给T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解析与.NET中的的XmlReader 类中的XML文件,我认为这将是明智的编写一个通用的解析函数,一般读取不同的属性。我想出了以下功能:

I'm parsing an XML file with the XmlReader class in .NET and I thought it would be smart to write a generic parse function to read different attributes generically. I came up with the following function:

private static T ReadData<T>(XmlReader reader, string value)
{
    reader.MoveToAttribute(value);
    object readData = reader.ReadContentAsObject();
    return (T)readData;
}



随着我逐渐认识到,这并不完全是工作,我已经计划;它抛出与基本类型的错误,如 INT 双击,因为投不能从<$ C $转换C>字符串为数值型。有什么办法为我的功能,在修改的形式为准?

As I came to realise, this does not work entirely as I have planned; it throws an error with primitive types such as int or double, since a cast cannot convert from a string to a numeric type. Is there any way for my function to prevail in modified form?

推荐答案

首先查看它是否可以转换。

First check to see if it can be cast.

if (readData is T) {
    return (T)readData;
} else {
    try {
       return (T)Convert.ChangeType(readData, typeof(T));
    } catch (InvalidCastException) {
       return default(T);
    }
}

这篇关于投对象给T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆