c# - 如何使用反射获取命名空间、类、方法及其参数

标签 c# .net dll reflection types

我需要使用 reflection 加载 dll 并且必须获取 namespaceclassmethods 及其 arguments 用于该 dll。另外,我需要将这些信息写入日志文件。

我使用了以下代码。但我只得到了已写入日志文件的类。

Assembly dll = Assembly.LoadFile(@"D:\Assemblies\Myapplication.dll");
foreach (Type type in dll.GetTypes())
{
    var name = "Myapplication~" + type.FullName;
    File.AppendAllText("Assembly Details.log", "Myapplication~" + type.FullName + "\r\n\r\n");

    Console.WriteLine(type.FullName);
}

在日志文件中,需要写入如下信息。

Myapplication~namespace.class~method(arguments)

例如:

Myapplication~copyassembly.class~Mymethod(String, Type)

任何建议都会非常有帮助。

最佳答案

你可以写一个类似这样的代码

Assembly dll = Assembly.LoadFile(@"C:\YourDirectory\YourAssembly.dll");

foreach (Type type in dll.GetTypes())
{
    var details = string.Format("Namespace : {0}, Type : {1}", type.Namespace, type.Name);
    //write details to your log file here...
    Console.WriteLine(details);

    foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
    {
        var methodDetails = string.Format("{0} {1}({2})", method.ReturnParameter, method.Name, 
                                            string.Join(",", method.GetParameters().Select(p => p.ParameterType.Name)));
        //write methodDetails to your log file here...
        Console.WriteLine("\t" + methodDetails);
    }
}

哪些会写这些细节

Namespace : MyNamespace.Helpers, Type : Constants
    System.String  ToString()
    Boolean  Equals(Object)
    Int32  GetHashCode()
    System.Type  GetType()
Namespace : MyNamespace.Helpers, Type : FileHelper
    Void  WriteToFile(String,String,String,String)
    Void  UpdateFile(String,String,Boolean)

在这里,您可以 [1] 根据需要更改 BindingFlags [2] 更改日志字符串的格式(详细信息/方法详细信息) [3] 根据需要格式化集合/通用类型

编辑
如果你想在没有返回类型的情况下显示,只需将其格式化为

var methodDetails = string.Format("{1}({2})", 
                                  method.Name, 
                                  string.Join(",", method.GetParameters().Select(p => p.ParameterType.Name)));

关于c# - 如何使用反射获取命名空间、类、方法及其参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523717/

相关文章:

c# - 与 EntityFramework 的命名冲突

c# - 什么值?? 0 表示在 C# 代码中

c# - .NET 4.0 中的 SpellCheck.IsEnabled ="True"(不适用于德语 .NET 4.0 框架)

c# - Windows 命令提示符中的 "Did you mean to run dotnet SDK commands? Please install dotnetsdk"

.net - 以编程方式获取表的外键约束

c# - 如何使用 Npoco FetchOneToMany?

c# - 无法在 protected 方法的单元测试的适当方法之间做出决定

java - 无法将 jzmq.dll 加载到 java 中

c# - 如何创建将在 C# 中使用的 DLL

c++ - 应用程序无法启动,因为它无法找到或加载 QT 平台插件 "windows"