【发布时间】:2011-12-01 05:10:50
【问题描述】:
我是 lambda 新手,所以如果我的描述中缺少重要信息,请告诉我。我将尽可能简单地保持示例。
我正在检查别人的代码,他们有一个类继承自另一个类。这是派生类,以及我无法理解的 lambda 表达式:
class SampleViewModel : ViewModelBase
{
private ICustomerStorage storage = ModelFactory<ICustomerStorage>.Create();
public ICustomer CurrentCustomer
{
get { return (ICustomer)GetValue(CurrentCustomerProperty); }
set { SetValue(CurrentCustomerProperty, value); }
}
private int quantitySaved;
public int QuantitySaved
{
get { return quantitySaved; }
set
{
if (quantitySaved != value)
{
quantitySaved = value;
NotifyPropertyChanged(p => QuantitySaved); //where does 'p' come from?
}
}
}
public static readonly DependencyProperty CurrentCustomerProperty;
static SampleViewModel()
{
CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(ICustomer),
typeof(SampleViewModel), new UIPropertyMetadata(ModelFactory<ICustomer>.Create()));
}
//more method definitions follow..
注意上面对NotifyPropertyChanged(p => QuantitySaved) 的调用。我不明白“p”是从哪里来的。
这是基类:
public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IXtremeMvvmViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged<T>(Expression<Func<ViewModelBase, T>> property)
{
MvvmHelper.NotifyPropertyChanged(property, PropertyChanged);
}
}
其中有很多内容与我确定的问题无关,但我想在包容性方面犯错。
问题是,我不明白“p”参数的来源,以及编译器如何知道(显然?)凭空填充 ViewModelBase 的类型值?
为了好玩,我将代码从“p”更改为“this”,因为 SampleViewModel 继承自 ViewModelBase,但我遇到了一系列编译器错误,其中第一个是 Invalid expression term '=>' 这让我有点困惑,因为我认为这会起作用。
谁能解释这里发生了什么?
【问题讨论】: