C# Reflection: Instantiate an object with string class name

后端 未结 6 1948
礼貌的吻别
礼貌的吻别 2020-12-30 10:22

my situation is the next: I\'m working with Visual C# 2010 express developing a Windows Forms Application. When the user logins, dinamically build a menustrip with options l

6条回答
  •  灰色年华
    2020-12-30 11:19

    You're trying to use the name of the class without specifying the namespace. This should be fine:

    Assembly assembly = Assembly.Load("AccountingSA");
    Type t = assembly.GetType("AccountingSA.Contabilidad");
    Form frmConta = (Form)Activator.CreateInstance(t);
    

    Every version of GetType requires the fully-qualified type name; the benefit of using Assembly.GetType is that at least you don't need to also include the assembly name, but as documented you still need the namespace:

    The name parameter includes the namespace but not the assembly.

    Note that to diagnose something similar in the future, it would have been worth looking at the value of t after the second line - it will be null, which is why the third line threw an exception.

提交回复
热议问题