简体   繁体   English

从类型对象转换为类型

[英]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. 有了这些信息,我需要在运行时将obMyClass How do I do this? 我该怎么做呢?

Convert.ChangeType is what you are looking for. 您正在寻找Convert.ChangeType

// 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: 假设MyClass在编译时是已知的:

object ob = new MyClass();

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

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

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