我需要使用 reflection
加载 dll
并且必须获取 namespace
、class
、methods
及其 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/