使用Lambda识别属性名称 [英] Using lambda to identify property name

查看:50
本文介绍了使用Lambda识别属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码有疑问:

public class MyClass : INotifyPropertyChanged
{
    private bool _myProp;
    public bool MyProp
    {
        get { return _myProp; }
        set
        {
            _myProp = value;                
            RaisePropertyChanged(() => MyProp);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

这可能不是识别属性名称的最佳方法,但是我以前使用过它,即使在同一项目中也是如此.但是,以上代码无法编译.有几种解决方法.其中一些可能是比上面更好的解决方案,但是,我仍然想找出为什么这不起作用.

This may not be the best way to identify a property name, but I have used it before, even in the same project; however, the above code won't compile. There's several workarounds for this; some of which may be better solutions that what is above, however, I'd still like to find out why this doesn't work.

我得到的具体编译错误是:

The specific compile error I get is:

error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

推荐答案

您需要一种方法,该方法接受 Expression< Func< T>> ,将属性名称提取为字符串,然后引发 PropertyChanged 事件.它不会自动完成.我通常将其作为扩展方法,以免一遍又一遍地实现相同的代码或将其保存在基类中.

You need a method that accepts Expression<Func<T>>, extracts the property name as a string, and then raises the PropertyChanged event with it. It won't be done automatically. I usually make it an extension method, to save implementing the same code over and over or having it in a base class:

public static class RaisePropertyChangedExtensions
{
    public static void RaisePropertyChanged<T>(
        this IRaisePropertyChanged raisePropertyChangedImpl,
        Expression<Func<T>> expr)
    {
        var memberExprBody = expr.Body as MemberExpression;
        string property = memberExprBody.Member.Name;
        raisePropertyChangedImpl.RaisePropertyChanged(property);
    }
}

您的视图模型只需要实现 IRaisePropertyChanged 接口:

Your view-models just need to implement the IRaisePropertyChanged interface:

public interface IRaisePropertyChanged : INotifyPropertyChanged
{
    void RaisePropertyChanged(string property);
}

..并且用法与您的问题完全相同:

..and the usage is exactly the same as in your question:

this.RaisePropertyChanged(() => MyProp);

当然,您始终可以将其作为视图模型的一种方法-只需删除通用参数并将视图模型类型传递给函数即可.

Of course, you can always make this a method on your view-model - just remove the generic parameter and pass your view-model type to the function.

这篇关于使用Lambda识别属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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