给定 .NET 中的 Type 对象,我可以获取源代码文件名吗?我知道这只能在 Debug 版本中使用,这很好,我也知道我可以使用 StackTrace 对象来获取调用堆栈中特定帧的文件名,但这不是我想要的。
但是我有可能获得给定 System.Type 的源代码文件名吗?
给定 .NET 中的 Type 对象,我可以获取源代码文件名吗?我知道这只能在 Debug 版本中使用,这很好,我也知道我可以使用 StackTrace 对象来获取调用堆栈中特定帧的文件名,但这不是我想要的。
但是我有可能获得给定 System.Type 的源代码文件名吗?
I encountered a similar problem. I needed to found the file name and line number of a specific method with only the type of the class and the method name. I'm on an old mono .net version (unity 4.6). I used the library cecil, it provide some helper to analyse your pbd (or mdb for mono) and analyse debug symbols. https://github.com/jbevain/cecil/wiki
For a given type and method:
System.Type myType = typeof(MyFancyClass);
string methodName = "DoAwesomeStuff";
I found this solution:
Mono.Cecil.ReaderParameters readerParameters = new Mono.Cecil.ReaderParameters { ReadSymbols = true };
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(string.Format("Library\\ScriptAssemblies\\{0}.dll", assemblyName), readerParameters);
string fileName = string.Empty;
int lineNumber = -1;
Mono.Cecil.TypeDefinition typeDefinition = assemblyDefinition.MainModule.GetType(myType.FullName);
for (int index = 0; index < typeDefinition.Methods.Count; index++)
{
Mono.Cecil.MethodDefinition methodDefinition = typeDefinition.Methods[index];
if (methodDefinition.Name == methodName)
{
Mono.Cecil.Cil.MethodBody methodBody = methodDefinition.Body;
if (methodBody.Instructions.Count > 0)
{
Mono.Cecil.Cil.SequencePoint sequencePoint = methodBody.Instructions[0].SequencePoint;
fileName = sequencePoint.Document.Url;
lineNumber = sequencePoint.StartLine;
}
}
}
I know it's a bit late :) but I hope this will help somebody!
我使用这样的代码从正在运行的方法中获取源文件和行号:
//must use the override with the single boolean parameter, set to true, to return additional file and line info
System.Diagnostics.StackFrame stackFrame = (new System.Diagnostics.StackTrace(true)).GetFrames().ToList().First();
//Careful: GetFileName can return null even though true was specified in the StackTrace above. This may be related to the OS on which this is running???
string fileName = stackFrame.GetFileName();
string process = stackFrame.GetMethod().Name + " (" + (fileName == null ? "" : fileName + " ") + fileLineNumber + ")";
考虑到至少 C# 支持部分类声明(例如,public partial class Foo
在两个源代码文件中),“给定 System.Type 的源代码文件名”是什么意思?如果一个类型声明分布在同一个程序集中的多个源代码文件中,则源代码中没有一个点是声明开始的地方。
@Darin Dimitrov:这看起来不像“如何获取源文件名和类型成员的行号?”的重复。对我来说,因为那是关于 type member,而这个问题是关于type。