根据字符串将对象强制转换为某种类型

时间:2017-06-29 09:27:47

标签: c# casting

我有一个'basetype'对象,我希望将其转换为特定类型。我想使这个通用,所以我希望获得对象的名称并将其转换为具有相同名称的类。像这样:

string name = baseObj.name;

var baseObj = baseObj as getClassFor(name);

我找到了Activator,但是我认为我是Activator.CreateInstance(),我认为不是我需要的。

我的问题是,如何根据字符串将对象转换为某种类型?

1 个答案:

答案 0 :(得分:1)

由于转换主要是编译时间,因此您无法根据字符串转换为特定类型,因此您必须使用dynamic关键字。

var t= Type.GetType(baseObj.name); //This should contain the correct namespace too. ex. "MyNamespace.SpecificClass"
dynamic specificObj = Convert.ChangeType(baseObj, t);
specificObj.SpecificMethod();
相关问题