C# 简单反射加载 DLL 实例

// 反射判断是否位某个类型

public bool IsSubclassOf(this Type type, Type baseType)
{
    // 如果type不是null并且baseType是一个类(非接口)
    if (type != null && baseType.IsClass)
    {
        return type.IsSubclassOf(baseType);
    }

    // 或者如果baseType是接口,并且type实现了该接口
    return baseType.IsInterface && type.GetInterfaces().Contains(baseType);
}

// 反射加载 DLL

// 加载插件方法 处理方法
public bool LoadPlugin()
{
    DirectoryInfo dir = new DirectoryInfo(DirName);
    if (!dir.Exists)
    {
        return false;
    }
    foreach (FileInfo fileInfo in dir.GetFiles("*.dll"))
    {
        try
        {
            byte[] buffer = File.ReadAllBytes(fileInfo.FullName);
            Assembly asm = Assembly.Load(buffer); // 这样不会占用文件
            Type[] types = asm.GetTypes();
            foreach (Type tp in types)
            {
                if (tp.GetInterface(typeof(IDev).Name) != null) // 如果是 IDev 接口类型
                {
                    PluginList.Add(new ModPlugin(Activator.CreateInstance(tp) as IDev));
                }
            }

            return true;
        }
        catch
        {
            continue;
        }
    }

    return true;
}
posted @ 2024-02-27 20:17  double64  阅读(111)  评论(0)    收藏  举报