如何在c#中访问父对象

Jea*_*rez 30 c# oop parent

我有一个"米"级."米"的一个属性是另一个叫做"生产"的类.我需要通过参考从生产类访问米级(额定功率)的属性.在仪表实例化时不知道powerRating.

我怎样才能做到这一点 ?

提前致谢

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production();
   }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ian 43

存储对作为生产成员的仪表实例的引用:

public class Production {
  //The other members, properties etc...
  private Meter m;

  Production(Meter m) {
    this.m = m;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在Meter级:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您需要实现一个访问器方法/属性,以便Production类可以实际访问Meter类的powerRating成员.

  • @Snowy:由于循环引用是不可能的,您需要重新排列实现并将一个类移动到另一个程序集(或者复制该类,如果没有别的帮助). (2认同)

小智 32

我不会直接在子对象中引用父级.在我看来,孩子们对父母一无所知.这将限制灵活性!

我会用事件/处理程序解决这个问题.

public class Meter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production();
        _production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
        _production.DoSomething();
    }
}

public class Production
{
    protected int RequestPowerRating()
    {
        if (OnRequestPowerRating == null)
            throw new Exception("OnRequestPowerRating handler is not assigned");

        return OnRequestPowerRating();
    }

    public void DoSomething()
    {
        int powerRating = RequestPowerRating();
        Debug.WriteLine("The parents powerrating is :" + powerRating);

    }

    public Func<int> OnRequestPowerRating;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我用Func <>泛型解决了它,但可以用'普通'函数完成.这就是为什么孩子(生产)完全独立于它的父母(米).


但!如果有太多事件/处理程序或者您只想传递父对象,我将使用接口解决它:

public interface IMeter
{
    int PowerRating { get; }
}

public class Meter : IMeter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production(this);
        _production.DoSomething();
    }

    public int PowerRating { get { return _powerRating; } }
}

public class Production
{
    private IMeter _meter;

    public Production(IMeter meter)
    {
        _meter = meter;
    }

    public void DoSomething()
    {
        Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
    }
}
Run Code Online (Sandbox Code Playgroud)

这看起来与解决方案提到的几乎相同,但是接口可以在另一个程序集中定义,并且可以由多个类实现.


此致,Jeroen van Langen.


bwa*_*ner 9

您需要向Production类添加一个属性,并将其设置为指向其父级,默认情况下不存在.