Wil*_*sem 16 c# methods class instance
我正在寻找一种算法,可以在该方法中获取调用该方法的对象.
例如:
public class Class1 {
public void Method () {
//the question
object a = ...;//the object that called the method (in this case object1)
//other instructions
}
}
public class Class2 {
public Class2 () {
Class1 myClass1 = new Class1();
myClass1.Method();
}
public static void Main () {
Class2 object1 = new Class2();
//...
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
Tra*_*er1 14
这是一个如何做到这一点的例子......
...
using System.Diagnostics;
...
public class MyClass
{
/*...*/
//default level of two, will be 2 levels up from the GetCaller function.
private static string GetCaller(int level = 2)
{
var m = new StackTrace().GetFrame(level).GetMethod();
// .Name is the name only, .FullName includes the namespace
var className = m.DeclaringType.FullName;
//the method/function name you are looking for.
var methodName = m.Name;
//returns a composite of the namespace, class and method name.
return className + "->" + methodName;
}
public void DoSomething() {
//get the name of the class/method that called me.
var whoCalledMe = GetCaller();
//...
}
/*...*/
}
Run Code Online (Sandbox Code Playgroud)
发布这个,因为我花了一段时间才找到自己正在寻找的东西.我在一些静态记录器方法中使用它...
use*_*uld -10
显然,我不知道您情况的确切细节,但这似乎您确实需要重新考虑一下您的结构。
如果构建适当的继承,这可以很容易地完成。
考虑研究一个抽象类和从该抽象类继承的类。您甚至可以使用接口来完成同样的事情。