在运行时,如何测试属性是否只读?

MoS*_*Slo 7 c# properties

我自动生成代码,根据配置(textboxes,dateTimePickers等)创建一个winform对话框.这些对话框上的控件是从保存的数据集中填充的

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

//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;
Run Code Online (Sandbox Code Playgroud)

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

//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;
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ell 7

PropertyDescriptor,检查IsReadOnly.

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

您可能还需要检查[ReadOnly(true)]的情况下PropertyInfo(但已与处理PropertyDescriptor):

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

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


小智 5

我注意到在使用 PropertyInfo 时,CanWrite即使 setter 是私有的,该属性也是 true。这个简单的检查对我有用:

bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;
Run Code Online (Sandbox Code Playgroud)