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

C# 在运行时,如何测试属性是否为只读?,c#,properties,C#,Properties,我正在自动生成基于配置(文本框、日期时间选择器等)创建winform对话框的代码。这些对话框上的控件由保存的数据集和 需要设置和获取各种控件对象(自定义或其他)的属性 现在这一切都很好,但是只读属性呢?我希望保存属性的结果,但需要知道何时不生成试图填充它的代码 //Open form, attempt to populate control properties. //Code that will result in 'cannot be assigned to -- it is read on

我正在自动生成基于配置(文本框、日期时间选择器等)创建winform对话框的代码。这些对话框上的控件由保存的数据集和

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

现在这一切都很好,但是只读属性呢?我希望保存属性的结果,但需要知道何时不生成试图填充它的代码

//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;
请记住,直到运行时我才知道实例化的对象的类型


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

使用
PropertyDescriptor
,选中
IsReadOnly

使用
PropertyInfo
,选中
CanWrite
(以及
CanRead

如果是
PropertyInfo
,您可能还需要检查
[ReadOnly(true)]
(但这已经由
PropertyDescriptor处理过了):

在我看来,
PropertyDescriptor
是一个更好的模型;它将允许定制模型。

此外-


我注意到,在使用PropertyInfo时,
CanWrite
属性是真的,即使setter是私有的。这张简单的支票对我有效:

bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;

我需要将其用于不同的类,因此我创建了这个通用函数:

public static bool IsPropertyReadOnly<T>(string PropertyName)
{
    MemberInfo info = typeof(T).GetMember(PropertyName)[0];

    ReadOnlyAttribute attribute = Attribute.GetCustomAttribute(info, typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;

    return (attribute != null && attribute.IsReadOnly);
}
公共静态bool IsPropertyReadOnly(字符串PropertyName)
{
MemberInfo=typeof(T).GetMember(PropertyName)[0];
ReadOnlyAttribute属性=属性。GetCustomAttribute(信息,类型(ReadOnlyAttribute))作为ReadOnlyAttribute;
返回(attribute!=null&&attribute.IsReadOnly);
}

在我看来,如果属性是只读的,用户就不能从UI表单中修改它。似乎当前所有属性都允许在表单上编辑,并且您在语句中保存?Truth时检查它们,但这是自动生成的代码。错误发生在编译时。我唯一一次得到“无法分配到”将是在生成的代码从保存的内容填充控件的属性时,从而意外地将保存的值分配给只读属性。
using System.ComponentModel;

// Get the attributes for the property.

AttributeCollection attributes = 
   TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;

// Check to see whether the value of the ReadOnlyAttribute is Yes.
if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
   // Insert code here.
}
bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;
public static bool IsPropertyReadOnly<T>(string PropertyName)
{
    MemberInfo info = typeof(T).GetMember(PropertyName)[0];

    ReadOnlyAttribute attribute = Attribute.GetCustomAttribute(info, typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;

    return (attribute != null && attribute.IsReadOnly);
}