C# Reflection: Instantiate an object with string class name

后端 未结 6 1906
礼貌的吻别
礼貌的吻别 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:00

    Try specifying your class this way:

    ContabilidadNamespace.Contabilidad, ContabilidadAssembly
    
    0 讨论(0)
  • 2020-12-30 11:06

    Try this

    Form frmConta= (Form)Activator.CreateInstance(null, "AccountingSA.Contabilidad").Unwrap();
    
    0 讨论(0)
  • 2020-12-30 11:09

    Use the fully-qualified name of the type:

    Type t = assembly.GetType("AccountingSA.Contabilidad");
    

    From the documentation for Assembly.GetType(string):

    name Type: System.String The full name of the type. [...] The name parameter includes the namespace but not the assembly.

    0 讨论(0)
  • 2020-12-30 11:18

    You should add the namespace:

    assembly.GetType("AccountingSA.Contabilidad");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 11:19

    Its too late in the thread to answer, but the earlier answer, in current .NET framework (4.7), not working (The line Assembly assembly = Assembly.Load("AccountingSA"); always throws FileIOException). Currently, working code is (Use Type directly)

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

    or other way using Assembly is

    Assembly assembly = typeof(Form).Assembly;
    Type t = assembly.GetType("AccountingSA.Contabilidad");
    Form frmConta = (Form)Activator.CreateInstance(t);
    
    0 讨论(0)
提交回复
热议问题