获取在C#中调用方法的实例

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)

发布这个,因为我花了一段时间才找到自己正在寻找的东西.我在一些静态记录器方法中使用它...

  • 而已!我真的不赞成像@Lazarus那样的评论('为什么你甚至需要这个'),甚至更多的是他们正在投票.我需要这个与你完全相同的东西,静态记录器由许多线程调用. (7认同)
  • 在发布模式下运行此命令,编译器将优化callstack,这将导致问题.在.NET 4.5中,现在有`CallerMemberName`属性 (6认同)
  • 我应该注意,这对你的需要不起作用,因为你想要给定对象的实例......在这种情况下你应该重新思考. (5认同)

use*_*uld -10

显然,我不知道您情况的确切细节,但这似乎您确实需要重新考虑一下您的结构。

如果构建适当的继承,这可以很容易地完成。

考虑研究一个抽象类和从该抽象类继承的类。您甚至可以使用接口来完成同样的事情。