简体   繁体   中英

Casting using System.Type - c#

Is it possible to cast an object to a desired type using 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.

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

看一下:

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() . This works if the type implement IConvertible , and if it is convertible to the desired type ( of course this is not a cast )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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