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

c# – CanRead和CanWrite对PropertyInfo意味着什么?

发布时间:2020-12-16 00:20:09 所属栏目:百科 来源:网络整理
导读:我正在编写一个类,根据其可访问性为属性生成 WPF绑定.这是关键方法: static Binding getBinding(PropertyInfo prop){ var bn = new Binding(prop.Name); bn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; if (prop.CanRead prop.CanWrite) b
我正在编写一个类,根据其可访问性为属性生成 WPF绑定.这是关键方法:

static Binding getBinding(PropertyInfo prop)
{
    var bn = new Binding(prop.Name);
    bn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    if (prop.CanRead && prop.CanWrite)
        bn.Mode = BindingMode.TwoWay;
    else if (prop.CanRead)
        bn.Mode = BindingMode.OneWay;
    else if (prop.CanWrite)
        bn.Mode = BindingMode.OneWayToSource;
    return bn;
}

但是,这没有按预期工作.当它应该是假的时候,CanWrite是真的.例如,对于此属性:

abstract class AbstractViewModel {
    public virtual string DisplayName { get; protected set; }
}

class ListViewModel : AbstractViewModel {
    //does not override DisplayName
}

我发现ListViewModel的DisplayName属性是CanRead和CanWrite.但是,如果我调用prop.GetAccessors(),则只列出get_DisplayName()访问器.

这里发生了什么?如果不是属性的保护级别,CanRead和CanWrite会指示什么?什么是我的方法的正确实现?

解决方法

What do CanRead and CanWrite indicate?

如果您有类似的问题,请先查看文档.

CanRead

If the property does not have a get accessor,it cannot be read.

CanWrite

If the property does not have a set accessor,it cannot be written to.

因此,属性指示是否存在get和set访问器,而不是它们的保护级别.其中一个原因是Reflection不知道你从哪里调用它,所以它不知道你是否可以实际访问访问器.

你可以做的是找出你是否可以访问访问器是调用GetGetMethod()GetSetMethod().如果属性没有公共get / set访问器,它们将返回null.

(编辑:李大同)

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

    推荐文章
      热点阅读