简体   繁体   中英

Casting to Type from Type Object

Consider my code:

public class MyClass
{
//...
}

object ob = new MyClass();
Type t = ob.GetType();

With this information, I need to cast ob to MyClass at run-time. How do I do this?

Convert.ChangeType is what you are looking for.

// With ob and t from your example.
var myClassInstance = Convert.ChangeType(ob, t);

But as some people suggest, it would be good to know why do you need this in the first place. Chances are there's a smell in your approach to the problem and it can be done easier, without any type kung-fu.

Assuming that MyClass is known at compile time:

object ob = new MyClass();

if (ob.GetType() != typeof(MyClass))
        MyClass convertedObject = (MyClass)ob;

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