开发者

How to load DLL and create a new instance in C#?

I want to load a DLL file if it exists, and create a new instance of it, cast it and pass to another function.

What I currently do is to add a reference to the DLL, and create an instance, e.g.,

ConfigFileSystemRegistry.Instance.RegisterFileSystem("er://", new Efs());

I tried to load it dynamically, but it's giving a System.TypeInitializationException

My code used is:

        if (File.Exists("plugin\\Efsystem.dll"))
        {
            Assembly assembly = Assembly.LoadFrom("plugin\\Efsystem.dll");
            Type type = assembly.GetType("Efs");
            ConfigFileSystemRegistry.Instance.RegisterFileSystem("er://", (IFileSystem) Activator.CreateInstance(type))开发者_JAVA百科;
        }


System.TypeInitializationException implies your static constructor is throwing an exception. Check the inner exception and the stack trace for hints.


You might want to check the existence of a default constructor. If there isn't, see what arguments you need, and call the override of CreateInstance with the params object[] args argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜