是否有一个良好的强类型的方式做在C#中的PropertyChanged事件? [英] Is there a good strongly typed way to do PropertyChanged events in C#?

查看:107
本文介绍了是否有一个良好的强类型的方式做在C#中的PropertyChanged事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它必须更改属性的名称,预计重命名功能,在Visual Studio中采取一切必要重命名的照顾,除了INotifyPropertyChanged的的PropertyChanged事件的属性名有点公共事件。有没有更好的办法以某种方式得到它强类型的,所以你不必记得手动将其重命名?

It must be a somewhat common event to change the name of a property and expect the Rename functionality in Visual Studio to take care of all the necessary renaming, except for the property name of the PropertyChanged event of INotifyPropertyChanged. Is there a better way to somehow get it strongly typed so you don't need to remember to manually rename it?

推荐答案

编辑: nameof 抵达C#6耶

有啊!没有 nameof / infoof 等;这是许多讨论,但它是什么。

There is no nameof / infoof etc; this is much discussed, but it is what it is.

有一种方法在.NET 3.5使用lambda表达式(和解析表达式树)做到这一点,但在现实中是不值得的开销。现在,我只是用绳子坚持(和单元测试,如果你坚决不打破它)。

There is a way to do it using lambda expressions in .NET 3.5 (and parsing the expression tree), but in reality it isn't worth the overhead. For now, I'd just stick with strings (and unit tests if you are determined not to break it).

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
class Program : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;
    static void Main() {
        var p = new Program();
        p.PropertyChanged += (s, a) => Console.WriteLine(a.PropertyName);
        p.Name = "abc";
    }
    protected void OnPropertyChanged<T>(Expression<Func<Program, T>> property) {
        MemberExpression me = property.Body as MemberExpression;
        if (me == null || me.Expression != property.Parameters[0]
              || me.Member.MemberType != MemberTypes.Property) {
            throw new InvalidOperationException(
                "Now tell me about the property");
        }
        var handler = PropertyChanged;
        if (handler != null) handler(this,
          new PropertyChangedEventArgs(me.Member.Name));
    }
    string name;
    public string Name {
        get{return name;}
        set {
            name = value;
            OnPropertyChanged(p=>p.Name);
        }
    }
}

这篇关于是否有一个良好的强类型的方式做在C#中的PropertyChanged事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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