简体   繁体   English

获取对象之间的引用

[英]Get reference from object to other

Following is my code block: 以下是我的代码块:

class MyClass: INotifyPropertyChanged
{
     ClearPendingBill cpb;
     public ClearPendingBill CPB
     {
        get { return cpb; }
        set
        {
            cpb = value;
            RaisePropertyChanged("CPB");
        }
     }
}

public partial class ClearPendingBill : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    double _selected_pending_amt = 0;
    public string SelectedPendingAmount
    {
        get { return "₹ " + string.Format("{0:0,0.00}", _selected_pending_amt); }
        set
        {
            SetField(ref _selected_pending_amt, Convert.ToDouble(value), "SelectedPendingAmount");
        }
    }
}

In the above code object of ClearPendingBill is created inside MyClass. 在上面的代码中,在MyClass内部创建了ClearPendingBill对象。 Is it possible somehow to refer MyClass object from ClearPendingBill object? 是否有可能以某种方式从ClearPendingBill对象引用MyClass对象?

Of course there is, you have to pass it on construction, or through some other method on ClearPendingBill . 当然,您必须在构造时通过它,或通过ClearPendingBill上的其他方法来传递它。

If you wrote: 如果您写了:

ClearPendingBill cpb = new ClearPendingBill(this);

It would give it a reference to the owning object (of course you need a constructor to handle it). 它将为拥有对象提供一个引用(当然,您需要一个构造函数来处理它)。 Static methods on MyClass are always accessible (as long as they are public). MyClass上的静态方法始终可以访问(只要它们是公共的)。

As written though, there is no way to get the owning object. 正如所写的那样,没有办法获得拥有的对象。

Not without a back-reference, because the object could be contained by multiple (or no) objects. 并非没有反向引用,因为该对象可能包含多个(或不包含)对象。

I assume you're wanting to notify the containing class that a property has changed. 我假设您要通知包含类属性已更改。 One way to do that is to have MyClass add a handler for the PropertyChanged event of the ClearPendingBill class. 一种方法是让MyClassClearPendingBill类的PropertyChanged事件添加一个处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM