C# 被调用者如何获取调用者的对象值?

public class A {
    public int n { get; set; }
    
    public void x() {
        B.y();
    }
}

public static class B {
    public static void y() {
        // 请问在不传参的条件下,有没有什么办法在这里拿到 a.n 的值?
    }
}

static void Main() {
    var a = new A() { n = 3 };
    a.x();
}
阅读 2.7k
2 个回答
新手上路,请多包涵

你这种场景有点奇怪。StackTrace类可以拿到,你查一下文档就会用了,不过性能就不好。

StackTrace 可以拿到调用者的 MethodBase,但是拿不到调用对象,所以做不到你想要的。要想拿到调用者对象,你必须把它作为参数传入 y()。不过,如果使用扩展方法 - C# 编程指南 | Microsoft Docs,可以近似满足你的需求。

public class A {
    public int n { get; set; }
    
    public void x() {
        this.y();   // 使用 this 调用扩展方法,会默认带入 this 参数
    }
}

public static class B {
    public static void y(this A a) {
        Console.WriteLine($"a.n = {a.n}");
    }
}

public class Program
{
    static void Main() {
        var a = new A() { n = 3 };
        a.x();
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进