简体   繁体   中英

How to get the “master caller” method class name inside a DLL in c#?

I'm currently doing a project on Unity3D with C# where I need to get the name of the "master caller" class name of a method and get it to a string. So far I've been using Stacktrace for it and its working marvellously.

This is the code used to achieve it:

string editorName = "Editor";
System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(0, true);

for ( int i = 1; !frame.GetFileName().Contains( editorName ) || frame.GetFileName().Contains( "InterfaceEditor" ); i++ )
{
    frame = new System.Diagnostics.StackFrame(i, true);
}

string method = frame.GetFileName(); //get the full path of the file that contains the class who called the getElements method
string[] splitSlash = method.Split ('\\'); //split the string with slash
string editorClassName = splitSlash [splitSlash.Length - 1].Split ('.') [0]; //get only the name of the file, without the .cs extension
string nameBody = editorClassName.Substring(0, editorClassName.Length - editorName.Length ); //get the substring that does not containt the "Editor" ending

An example of the call hierarchy goes like this:

JointEditor -> InterfaceEditor -> MultiLanguageParser

So the nameBody string in this example would be "Joint".

As I said this is working great so far, but now I have to make a DLL of this project and once this is done, the StackFrame begins to return NULL.

Is there another way to achieve the same result but on a DLL? I know that this will work if I start to pass the Class itself as a parameter to my final method, but I find this to be a very ugly solution, which is why the StackTrace solution was chosen in the first place.

I recommend using the "ugly method" you described, for three simple reasons:

  1. It's easier
  2. Navigating the stack trace during runtime is commonly regarded bad design.
  3. Reflection, especially on the stack trace, is painfuly slow (slightly exaggerated ;) ). And since your coding for unity3D I'm assuming, performance is a factor.

With these thoughts in mind, I'd propose passing the Type of the caller to the callee directly and work with the type.Name Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM