Ho provato entrambi i metodi di stakx.
Method based on MainModule non funziona in alcuni casi speciali (assiemi dinamici ad esempio).
Method based on StackTrace può restituire un assembly troppo alto (o basso) nella gerarchia, come mscorlib.
Ho fatto un po 'di variante che funziona bene nei miei casi d'uso:
// using System.Diagnostics;
// using System.Linq;
var methodFrames = new StackTrace().GetFrames().Select(t => t.GetMethod()).ToArray();
MethodBase entryMethod = null;
int firstInvokeMethod = 0;
for (int i = 0; i < methodFrames.Length; i++)
{
var method = methodFrames[i] as MethodInfo;
if (method == null)
continue;
if (method.Name == "Main" && method.ReturnType == typeof(void))
entryMethod = method;
else if (firstInvokeMethod == 0 && method.Name == "InvokeMethod" && method.IsStatic && method.DeclaringType == typeof(RuntimeMethodHandle))
firstInvokeMethod = i;
}
if (entryMethod == null)
entryMethod = firstInvokeMethod != 0 ? methodFrames[firstInvokeMethod - 1] : methodFrames.Last();
Assembly entryAssembly = entryMethod.Module.Assembly;
Fondamentalmente, io a piedi lo stack fino a quando ho trovato un metodo convenzionale denominato "Main" con void
tipo di ritorno. Se non viene trovato alcun metodo, cerco un metodo invocato tramite reflection. Ad esempio, NUnit utilizza tale chiamata per caricare i test unitari.
Naturalmente, lo faccio solo se Assembly.GetEntryAssembly()
restituisce null
.
fonte
2015-07-17 11:35:43