Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

后端 未结 13 2200
-上瘾入骨i
-上瘾入骨i 2020-11-22 17:21

Is it possible to instantiate an object at runtime if I only have the DLL name and the class name, without adding a reference to the assembly in the project? The class imple

相关标签:
13条回答
  • 2020-11-22 17:48

    You can do this things on this way:

    using System.Reflection;
    
    Assembly MyDALL = Assembly.Load("DALL"); //DALL name of your assembly
    Type MyLoadClass = MyDALL.GetType("DALL.LoadClass"); // name of your class
     object  obj = Activator.CreateInstance(MyLoadClass);
    
    0 讨论(0)
  • 2020-11-22 17:52

    Yes, it is, you will want to use the static Load method on the Assembly class, and then call then call the CreateInstance method on the Assembly instance returned to you from the call to Load.

    Also, you can call one of the other static methods starting with "Load" on the Assembly class, depending on your needs.

    0 讨论(0)
  • 2020-11-22 17:53

    Activator.CreateInstance ought to work.

    IFace object = (IFace)Activator.CreateInstance( "AssemblyName",
                                                    "TypeName" )
                                   .Unwrap();
    

    Note: The type name must be the fully qualified type.

    Example:

    var aray = (IList)Activator.CreateInstance("mscorlib","System.Collections.ArrayList").Unwrap();
    aray.Add(10);
    
    foreach (object obj in aray)
    {
        Console.WriteLine(obj);
    }
    
    0 讨论(0)
  • 2020-11-22 17:55

    Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

    Assembly assembly = Assembly.LoadFrom("MyNice.dll");
    
    Type type = assembly.GetType("MyType");
    
    object instanceOfMyType = Activator.CreateInstance(type);
    

    Update

    When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

    0 讨论(0)
  • 2020-11-22 17:55
    ((ISomeInterface)Activator.CreateInstance(Assembly.LoadFile("somePath").GetTypes()[0])).SomeInterfaceMethod();
    
    0 讨论(0)
  • 2020-11-22 17:56

    Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.

    In the meantime, this link should get you started:

    Using reflection to load unreferenced assemblies at runtime

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