Cast to a type from the type name as a string

前端 未结 2 1956
耶瑟儿~
耶瑟儿~ 2020-12-18 23:14

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 Do         


        
相关标签:
2条回答
  • 2020-12-18 23:35

    I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.

    If not, consider adding the behavior as an interface requirement so you can do it that way.

    Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.

    0 讨论(0)
  • 2020-12-18 23:48

    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)))

    Should work for you.

    0 讨论(0)
提交回复
热议问题