반사를 통해 DLL 동적 로드

1300 단어 .net
BaseInterface.dll
namespace BaseInterface
{
    public interface Test
    {
        string TestImpl();
    }
}

TestClass1.dll
using BaseInterface;

namespace TestClass1
{
    public class TestClass : Test
    {
        public string TestImpl()
        {
            return "TestClass1";
        }
    }
}

TestClass2.dll
using BaseInterface;

namespace TestClass2
{
    public class TestClass : Test
    {
        public string TestImpl()
        {
            return "TestClass2";
        }
    }
}

main
using System;
using System.Reflection;
using BaseInterface;

namespace         DLL
{
    class Program
    {
        static void Main(string[] args)
        {
            string dllPath = "TestClass1.dll";
            Assembly assembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\" + dllPath);
            Type type = assembly.GetType(dllPath.Replace(".dll", "") + ".TestClass");
            Object obj = (Test)Activator.CreateInstance(type);
            MethodInfo method = type.GetMethod("TestImpl");
            Console.WriteLine(method.Invoke(obj, null));
            Console.Read();
        }
    }
}

좋은 웹페이지 즐겨찾기