问题
Assume I have a simple script writing in C# 9 like this:
using System;
using System.IO;
// What to put in the ???
var exeFolder = Path.GetDirectoryName(typeof(???).Assembly.Location);
Before, with the full program, we can use the Main class as an "indicator" class. this and this.GetType() is not available because technically it's inside a static method. How do I get it now?
A workaround I thought of while typing the question is Assembly.GetCallingAssembly():
var exeFolder = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
It works for my case, but I can only get the Assembly, not the TypeInfo that in which the code is running.
回答1:
I suggest starting from the method which is executing (Main):
TypeInfo result = MethodBase
.GetCurrentMethod() // Executing method (e.g. Main)
.DeclaringType // Type where it's declared (e.g. Program)
.GetTypeInfo();
If you want Type, not TypeInfo drop the last method:
Type result = MethodBase
.GetCurrentMethod() // Executing method (e.g. Main)
.DeclaringType; // Type where it's declared (e.g. Program)
回答2:
You can also get the assembly using GetEntryAssembly.
Once you have the assembly that your code is in, you can get its EntryPoint, which is the compiler-generated "Main" method. You can then do DeclaringType to get the Type:
Console.WriteLine(Assembly.GetEntryAssembly().EntryPoint.DeclaringType);
The above should get the compiler-generated "Program" class even if you are not at the top level.
来源:https://stackoverflow.com/questions/65164165/how-do-i-get-the-reflection-typeinfo-of-a-c-sharp-9-program-that-use-top-level-s