c# - Lambda operator in set -
can explain purpose of lambda operator in piece of code, do?
public string helloworld { { return _helloworld; } set { set(() => helloworld, ref _helloworld, value); } }
this common pattern extract member name inotifypropertychanged
implementation.
usually, want raise propertychanged
event propertychangedeventargs
property name changed. problem property name string. if rename property, have make sure adjust member name strings too.
in order avoid that, people implement method, e.g. set
, takes expression. method uses expression tree extract member name of property. takes name create event arguments , raises event you.
your set
equivalent following setter:
set { if (_helloworld != value) { _helloworld = value; onpropertychanged(new propertychangedeventargs(this, "helloworld")); } }
and encapsulated in set
method provided base view model.
btw. .net 4.5, can make use of new compiler services make simpler. .net 4.5 comes callermembernameattribute
allows implementations of inotifypropertychanged
provide utility function automatically gets name of property, don’t have pass lambda expression references property. furthermore, new functionality evaluated @ compile time, same performance when pass string, except don’t need specify string anywhere, you’re safe against refactorings.
this functionality provided mvvm light, , can use different overload of set
use it. example this:
set(ref _helloworld, value);
with c# 6, can use new nameof
operator: nameof(helloworld)
replaced "helloworld"
@ compile time.
Comments
Post a Comment