【问题标题】:retrieving the reference to the calling class instance from a method in C#从 C# 中的方法检索对调用类实例的引用
【发布时间】:2012-06-19 19:01:16
【问题描述】:

我在 C# 中有以下场景

public class classA
{
public int fieldA = 1;

public classA()
{
    classB b=new classB();
    b.Execute();
}
}


public class classB
{
    public Execute() 
    {
        //I can get the type of classA using
        FieldInfo fi = stackTrace.GetFrame(1).GetMethod().DeclaringType
    }
}

问题是我如何获得在classB实例中调用Execute的classA的引用?

我尝试使用反射,但找不到任何方法。

任何帮助将不胜感激

【问题讨论】:

标签: c#


【解决方案1】:

您可以像这样在执行方法中将 A 的引用发送给 B:

b.Execute(this);

你可以通过这种方式到达对象A。

【讨论】:

    【解决方案2】:

    这样改B类

    public class B
    {
        public Execute(A aObj) 
        {
            //class A Object is available here
    
    
        }
    
    }
    

    这样改A类

    public class A
    
    {
       public A()
            {
    
                B b = new B();
                b.Execute(this);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      相关资源
      最近更新 更多