假设我在其中有一个静态类和一个静态方法。它必须由 10 个不同的类访问。但是静态类如何知道谁调用了它:(
这是一个面试问题....请正确改写并回答我,我是新来的:(
最佳答案
由于 C# 没有适当的元对象系统,我知道的唯一方法是通过反射。下面的思路应该给出思路:
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);
}
关于c# - 静态类的静态方法如何知道调用者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11594140/