【问题标题】:this not valid in the context这在上下文中无效
【发布时间】:2013-12-11 13:13:01
【问题描述】:

我的问题最初是删除一个匿名代表。我查看了找到here 的答案链。但是我的问题有点不同。由于某种原因,该方法 Hookup 编译。但变量处理程序没有。我得到的错误是“this”在上下文中无效......但为什么呢?为什么一个方法签名可以编译,而另一个没有?我可以在这里实现 lambda 格式吗?我真的很想实现 lambda 格式,因为我相信即使它是一个变量,它也更具可读性。但我真的对此很好奇,但到目前为止我还没有找到答案。

    protected void Hookup(object sender, PropertyChangedEventArgs args)
    {
        this.OnPropertyChanged(args.PropertyName);
    }

    protected PropertyChangedEventHandler hookup= (sender, arg) => this.OnPropertyChanged(arg.PropertyName);

完整代码在这里:

public abstract class Notifiable : INotifyPropertyChanged
{
    protected void Hookup(object sender, PropertyChangedEventArgs args)
    {
        this.OnPropertyChanged(args.PropertyName);
    }

    protected PropertyChangedEventHandler hookup = (sender, arg) => this.OnPropertyChanged(arg.PropertyName);

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged == null) return;
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    protected void OnObservableChanges(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
            foreach (var item in e.NewItems)
                (item as INotifyPropertyChanged).PropertyChanged += this.Hookup;//(osender, arg) => this.OnPropertyChanged(arg.PropertyName);
        if (e.OldItems != null)
            foreach (var item in e.OldItems)
                //This is the real reason for my problem. I need to be able to unhook the commented out anonymous call. 
                //As you can see, the lambda format is much easier to read and get the gist of what's up.
                (item as INotifyPropertyChanged).PropertyChanged -= this.Hookup;//(osender, arg) => this.OnPropertyChanged(arg.PropertyName);
    }
}

【问题讨论】:

    标签: c# lambda this


    【解决方案1】:

    因为您在这里为实例字段使用了变量初始化器:

    protected PropertyChangedEventHandler hookup= (sender, arg) => this.OnPropertyChanged(arg.PropertyName);
    

    但你不能这样做。

    来自C# specification

    10.5.5.2 10.5.5.2 实例字段初始化
    ...
    实例字段的变量初始值设定项不能引用正在创建的实例。因此,在变量初始化程序中引用this 是编译时错误,因为变量初始化程序通过简单名称引用任何实例成员是编译时错误。


    不过,你可以在构造函数中初始化hookup

    public abstract class Notifiable : INotifyPropertyChanged
    {
        protected PropertyChangedEventHandler hookup;
    
        public Notifiable()
        {
            hookup = (sender, arg) => OnPropertyChanged(arg.PropertyName);
        }
    
        ...
    }
    

    【讨论】:

    • 究竟是什么在逃避我。谢谢。
    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2013-10-30
    • 2012-09-27
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多