问题
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