如何让调用这个类的方法 [英] how to get invoker class of this method

查看:135
本文介绍了如何让调用这个类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?

我想要得到的类(类似foo),它调用我的方法(如myMethod的)

i want to get the name of class (like foo) which is invoking my method (like myMethod)

(和方法在另一个类(像我))

(and the method is in another class(like i))

这样的:

class foo
{
    i mc=new i;
    mc.mymethod();

}
class i
{
    myMethod()
    {........
       Console.WriteLine(InvokerClassName);// it should writes foo
    }
}

感谢

推荐答案

您可以使用的 堆栈跟踪 制定出呼叫者 - 但这是假设没有内联回事。堆栈跟踪并不总是100%准确。是这样的:

You can use StackTrace to work out the caller - but that's assuming there's no inlining going on. Stack traces aren't always 100% accurate. Something like:

StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1); // 0 will be the inner-most method
MethodBase method = frame.GetMethod();
Console.WriteLine(method.DeclaringType);

这篇关于如何让调用这个类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆