简体   繁体   English

使用System.Type进行强制转换 - c#

[英]Casting using System.Type - c#

Is it possible to cast an object to a desired type using System.Type? 是否可以使用System.Type?将对象System.Type?转换为所需类型System.Type? as the reference? 作为参考?

I had a search and the general consensus was no, although I was hoping there may be some aids introduced in C# 4.0 that could help me. 我有一个搜索,普遍的共识是否定的,虽然我希望在C#4.0中引入一些可以帮助我的辅助工具。

Ie the below will not work, but the pseudocode is what I would like. 即下面的内容不起作用,但伪代码就是我想要的。

object o = null;
var t = typeof(string);
...
string foo = (t)o;

Edit: I need use XmlSerializer to reconstruct / deserialize to the type stored in t 编辑:我需要使用XmlSerializer重建/反序列化为存储在t的类型

看一下:

var foo = Convert.ChangeType(o, typeof(string))

That doesn't make sense. 这没有意义。

Casting doesn't change an object at all; 铸造根本不会改变对象; it just lets you use the object as the given type at compile-time . 它只是让你在编译时使用对象作为给定的类型。
If you don't know what type you're casting it to at compile-time , the cast is useless, since it wouldn't let you do anything with the casted expression. 如果您不知道在编译时将其转换为什么类型,则转换是无用的,因为它不会让您对转换表达式执行任何操作。

No need to cast. 不需要施放。 The object doesn't change, your type of references (variables) changes when "casting". 对象不会改变,“铸造”时您的引用类型(变量)会发生变化。

I guess you are looking for something like System.ChangeType() . 我想你正在寻找类似System.ChangeType()的东西。 This works if the type implement IConvertible , and if it is convertible to the desired type ( of course this is not a cast ) 如果类型实现了IConvertible ,并且它可以转换为所需类型(当然这不是强制转换) ,则此方法有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM