加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 是否可以将属性更改为属性?

发布时间:2020-12-15 23:44:08 所属栏目:百科 来源:网络整理
导读:我找到了一个Propperty Changed Event的实现,我可以在没有Web中属性名称的情况下更改Call Property.然后我在这里建立了一个扩展方法 public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged,string propertyName = null)
我找到了一个Propperty Changed Event的实现,我可以在没有Web中属性名称的情况下更改Call Property.然后我在这里建立了一个扩展方法

public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged,string    propertyName = null)
{
    if (propertyName == null)
        propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_","");
    FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged",BindingFlags.Instance | BindingFlags.NonPublic);
    if (field == (FieldInfo) null)
        return;
    object obj = field.GetValue((object) iNotifyPropertyChanged);
    if (obj == null)
        return;
    obj.GetType().GetMethod("Invoke").Invoke(obj,new object[2]
    {
        (object) iNotifyPropertyChanged,(object) new PropertyChangedEventArgs(propertyName)
    });
}

所以我可以将Property更改为:

private bool _foo;
public bool Foo
{
    get { _foo; }
    private set
    {
        _foo = value;
        this.OnPropertyChanged();
    }
}

但我想,如果我在使用Property更改时不必实现属性的getter和setter会更好.

现在有人如何将OnPropertyChanged方法作为属性实现,也许是用AOP?

因此,Auto-Property可用于Property Changed,如下所示:

[OnPropertyChanged]
public bool Foo {set;get;}

解决方法

查看 Fody和 PropertyChanged加载项.它将在编译后修改IL,以添加代码以引发属性的PropertyChanged事件.它类似于在Lasse的回答中提到的PostSharp,但它是免费的和开源的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读