确定什么叫类的方法?什么叫、方法

2023-09-04 01:15:24 作者:初心i

这是一个有点假设所以我承担。我心目中的应用程序,但不知道如何做到这一点。说我有一个DLL不带参数的一些公开访问的方法。是否有可能为这个方法知道什么叫的吗?它知道它是从静态或实例化的背景下叫什么名字?从一个特定的类?什么方法知道它是如何被调用?

This is a little hypothetical so bear with me. I have an application in mind, but not sure how to do this. Say I have some publically accessible method in a DLL that takes no parameters. Is it possible for this method to know what called it? Can it tell if it were called from a static or instantiated context? From a specific class? What can a method know about how it's being called?

推荐答案

您可以从堆栈跟踪获取来电信息:

You can get caller info from stack trace:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();

是否有可能为这种方法知道什么叫的吗?

Is it possible for this method to know what called it?

string typeName = methodBase.DeclaringType.Name;
string methodName = methodBase.Name;

可不可以这样说,如果它是从静态或实例化的背景下叫什么名字?

Can it tell if it were called from a static or instantiated context?

bool isStaticCall = methodBase.IsStatic

从一个特定的类?

From a specific class?

bool isGeneric = methodBase.DeclaringType.IsGenericType;