提升propertychanged事件,而不添加专用变量 [英] Raising a propertychanged event without adding a private variable

查看:109
本文介绍了提升propertychanged事件,而不添加专用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的属性。



 公众诠释NumberOfElephants {搞定;组; } 



此属性是一个ObservableCollection,它有通知,它已经改变了另一个属性。



如何将我做以下

 公众诠释NumberOfElephants {搞定;集合{OnPropertyChanged(totalAnimals); } 



无码需要是这样

 私人诠释_numberOfElephants; 
公众诠释NumberOfElephants {
获得{
返回_numberOfElephants;
}

集合{
_numberOfElephants =价值;
OnPropertyChanged(totalAnimals);
}
}


解决方案

您别。你不能



自动实现属性的只有的工作时,该属性是微不足道的 - 当需要为获取无码/套超越返回变量的值或设置变量的值。你可以把它与重新格式化,当然更短......我会写为:

 私人诠释numberOfElephants; 
公众诠释NumberOfElephants {
{返回numberOfElephants; }

集合{
_numberOfElephants =价值;
OnPropertyChanged(totalAnimals);
}
}



其实,我会使用在左括号行自身为集的开始和财产的开始,但我已经把你喜欢的风格的。但是,在一行有单一的表达 GET / 实现可以有很多的属性更清洁做的类。


I have a property which looks like this.

public int NumberOfElephants { get; set; }

this property is in an observablecollection and it has to notify another property that it has changed.

how would i do the following

public int NumberOfElephants { get; set { OnPropertyChanged("totalAnimals"); }

without the code needing to be like this

private int _numberOfElephants;
public int NumberOfElephants { 
    get { 
        return _numberOfElephants; 
    } 

    set { 
        _numberOfElephants = value; 
        OnPropertyChanged("totalAnimals"); 
    } 
}

解决方案

You don't. You can't.

Automatically implemented propertieS only work when the property is trivial - when no code is needed for the get/set beyond "return the variable's value" or "set the variable's value". You can make it shorter with reformatting, of course... I'd write that as:

private int numberOfElephants;
public int NumberOfElephants {
    get { return numberOfElephants; }

    set {
        _numberOfElephants = value; 
        OnPropertyChanged("totalAnimals"); 
    } 
}

Actually, I'd use "opening brace on a line on its own" for the start of the set and the start of the property, but I've kept your favoured style for those. But having "single expression get/set implementations" on a single line can make classes with lots of properties much cleaner.

这篇关于提升propertychanged事件,而不添加专用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆