将对象投射到 T [英] Cast object to T
本文介绍了将对象投射到 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
或 double
之类的原始类型的错误,因为强制转换无法从 string
转换为数字类型.有什么办法可以让我的函数以修改后的形式占上风?
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;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
这篇关于将对象投射到 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文