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

c# – CanRead和CanWrite对PropertyInfo意味着什么?,第1张

概述我正在编写一个类,根据其可访问性为属性生成 WPF绑定.这是关键方法: static Binding getBinding(PropertyInfo prop){ var bn = new Binding(prop.Name); bn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; if (prop.C 我正在编写一个类,根据其可访问性为属性生成 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.

总结

以上是内存溢出为你收集整理的c# – CanRead和CanWrite对PropertyInfo意味着什么?全部内容,希望文章能够帮你解决c# – CanRead和CanWrite对PropertyInfo意味着什么?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1223501.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存