【问题标题】:use reflection to search in DLLs c#使用反射在 DLL 中搜索 c#
【发布时间】:2013-11-27 19:53:30
【问题描述】:

目前我正在使用反射在我的程序集中搜索实现接口的类,然后检查这些类的名称以查看它是否与正在搜索的类匹配。

我的下一个任务是在此代码中添加一种在目录中搜索 DLL 文件的方法,我唯一的提示是我可以使用“System.Environment.CurrentDirectory”。我还需要考虑并非所有 DLL 都包含 .net 程序集这一事实。

谁能推荐从哪里开始?

        IInstruction instruction = null;
        string currentDir = Environment.CurrentDirectory;

        var query = from type in Assembly.GetExecutingAssembly().GetTypes()
                    where type.IsClass && type.GetInterfaces().Contains(typeof(IInstruction))
                    select type;

        foreach (var item in query)
        {
            if (opcode.Equals(item.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                instruction = Activator.CreateInstance(item) as IInstruction;
                return instruction;
            }
        }

opcode 是我正在搜索的类的名称。

【问题讨论】:

  • 您可以使用this 作为起点,当然指向您自己的目录而不是框架程序集目录。
  • @JoachimIsaksson 您能否更详细地解释您的答案,甚至可以举个例子?

标签: c# reflection dll


【解决方案1】:

这样的事情应该可以帮助您入门,它将尝试加载当前目录中的所有 .dll 文件并返回它们包含的所有类型,其短名称包含在 opcode 中;

private static IEnumerable<Type> GetMatchingTypes(string opcode)
{
    var files = Directory.GetFiles(Environment.CurrentDirectory, "*.dll");

    foreach (var file in files)
    {
        Type[] types;
        try
        {
            types = Assembly.LoadFrom(file).GetTypes();
        }
        catch
        {
            continue;  // Can't load as .NET assembly, so ignore
        }

        var interestingTypes =
            types.Where(t => t.IsClass &&
                             t.GetInterfaces().Contains(typeof (IInstruction)) &&
                             t.Name.Equals(opcode, StringComparison.InvariantCultureIgnoreCase));

        foreach (var type in interestingTypes)
            yield return type;
    }
}

【讨论】:

    【解决方案2】:

    对找到的 dll 使用Assembly.LoadFile 方法:

    foreach (var dllPath in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.dll"))
    {
        try
        {
            var assembly = Assembly.LoadFile(dllPath);
            var types = assembly.GetTypes();
        }
        catch (System.BadImageFormatException ex)
        {
            // this is not an assembly
        }
    }
    

    【讨论】:

    • 我可以使用 Assembly 程序集 = Assembly.LoadFile(currentDir);要搜索多个 DLL?
    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多