从类型名称转换为字符串 [英] Cast to a type from the type name as a string
问题描述
我有一个现有的基本类型,我想根据类型的名称将其强制转换为派生类型,即字符串,所以像这样:
I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
我很确定这是不可能完成的,但是肯定知道。谢谢
I'm pretty sure this can't be done but would be good to know for sure. Thanks
编辑:我知道我可以使用类型名称的反射来构造对象,但我想使用现有的对象。我也知道这通常是个坏主意。但是,我想将其用于SpecFlow BDD功能。
I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
推荐答案
我将重复您可能不需要的建议这样做,但是因为我之前已经做过此操作:
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast,Type.GetType(stringNameOfType)))
应该为您服务。
这篇关于从类型名称转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!