none
Is it possible to generate instance from class name? RRS feed

  • 问题

  • hi,

    For example, I hava a class, Apple is the classname.

    Is it possible to generate an Apple instance from the variable 'Apple'?

    Using the reflection, Activator.CreateInstance can only generate an object instance, is there any other methods can do it?

    Thanks.

    Jeffers

    2021年10月21日 1:53

全部回复

  • 您好,

    根据我的研究,目前来说,使用CreateInstance是根据类名来创建实例的唯一方法,如果你需要得到对应的类型实例,你可以使用强制类型转换,像下面这样:

    Assembly assem = typeof(Person).Assembly;
    
    Person p = (Person) assem.CreateInstance("Contoso.Libraries.Person");

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2021年10月21日 3:11
    版主