在运行时,如何测试属性是否为只读? [英] At runtime, how can I test whether a Property is readonly?

查看:40
本文介绍了在运行时,如何测试属性是否为只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自动生成基于配置(文本框、dateTimePickers 等)创建 winform 对话框的代码.这些对话框上的控件是从保存的数据集填充的,

I am auto-generating code that creates a winform dialog based on configuration (textboxes, dateTimePickers etc). The controls on these dialogs are populated from a saved dataset and

需要为各种控件对象(自定义或其他)设置和获取属性.

needs to Set and Get properties for various control objects (custom or other).

//Upon opening of form - populate control properties with saved values
MyObject.Value = DataSource.GetValue("Value");

//Upon closing of form, save values of control properties to dataset.
DataSource.SetValue("Value") = MyObject.Value;

现在一切都好了,但是 readOnly 属性呢?我希望保存属性的结果,但需要知道何时不生成将尝试填充它的代码.

Now this is all fine, but what of readOnly properties? I wish to save the result of the property but need to know when to NOT generate code that will attempt to populate it.

//Open form, attempt to populate control properties.
//Code that will result in 'cannot be assigned to -- it is read only'
MyObject.HasValue = DataSource.GetValue("HasValue");
MyObject.DerivedValue = DataSource.GetValue("Total_SC2_1v1_Wins");

//Closing of form, save values. 
DataSource.SetValue("HasValue") = MyObject.HasValue;

请记住,直到运行时我才知道我实例化的对象类型.

Remember that I do not know the type of object I've instantiate until runtime.

我如何(在运行时)识别只读属性?

How can I (at runtime) identify a readonly property?

推荐答案

使用 PropertyDescriptor,检查 IsReadOnly.

使用 PropertyInfo,检查 CanWrite(和 CanRead,就此而言).

With PropertyInfo, check CanWrite (and CanRead, for that matter).

您可能还想在 PropertyInfo 的情况下检查 [ReadOnly(true)](但这已经用 PropertyDescriptor 处理了):

You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor):

 ReadOnlyAttribute attrib = Attribute.GetCustomAttribute(prop,
       typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
 bool ro = !prop.CanWrite || (attrib != null && attrib.IsReadOnly);

IMO,PropertyDescriptor 是这里使用的更好模型;它将允许自定义模型.

IMO, PropertyDescriptor is a better model to use here; it will allow custom models.

这篇关于在运行时,如何测试属性是否为只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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