How the static class's static method will know the caller?

隐身守侯 提交于 2019-12-10 18:34:49

问题


Imagine I have a static class and a static method inside that. And it has to be accessed by 10 different classes. But how the static class will know who has called it :(

It was an interview question....please rephrase it properly and answer me, I am new :(


回答1:


I would try the following:

public class ParentClass
{
}

public class ChildClass :  ParentClass
{
}

public static class StaticClass
{
    public static void SomeMethod(ParentClass d)
    {
        var t = d.GetType();
    }
}

public class StaticChildren
{
    public void Children()
    {
        var p = new ChildClass();

        StaticClass.SomeMethod(p);

    }
}

Just passing an instance is the simplest you can do here.




回答2:


As C# does not have a proper metaobject system, the only way I know of is via reflection. The following idea should give the idea:

public static string GetCaller()
{
    var trace = new StackTrace(2);
    var frame = trace.GetFrame(0);
    var caller = frame.GetMethod();
    var callingClass = caller.DeclaringType.Name;
    var callingMethod = caller.Name;
    return String.Format("Called by {0}.{1}", callingClass, callingMethod);
}



回答3:


You could use the stracktace to find out who called the static method!

class Foo
{
  public void static staticMethod()
  {
    // here i want to know who called me!
    StackTrace st = new StackTrace();
    ...
  }
}

class Bar
{
  public void Bar()
  {
    Foo.staticMethod();
  }
}



回答4:


In these cases you can use Reflection.

Find more about reflection under these links: http://www.csharp-examples.net/reflection-calling-method-name/

http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx




回答5:


If the functionality of a method is dependent on who called it, then the design is probably not very good. I'd introduce new parameters instead.

for debugging purposes, a stack trace?



来源:https://stackoverflow.com/questions/11594140/how-the-static-classs-static-method-will-know-the-caller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!