使用反射读取属性的属性

本文关键字:属性 读取 反射 | 更新日期: 2023-09-27 18:07:12

我需要使用反射读取属性的属性

例如:

    [XmlElement("Id")]
    [CategoryAttribute("Main"), ReadOnly(true),
    Description("This property is auto-generated")]
    [RulesCriteria("ID")]
    public override string Id
    {
        get { return _ID; }
        set
        {
            _ID = value;
        }
    }

我想使用反射获得该属性的"只读"值有谁能帮忙吗

使用反射读取属性的属性

在不知道类型名称的情况下编写代码是很困难的。希望下面的例子有所帮助。

using System;
using System.Reflection;
public class Myproperty
{
    private string caption = "Default caption";
    public string Caption
    {
        get{return caption;}
        set {if(caption!=value) {caption = value;}
        }
    }
}
class Mypropertyinfo
{
    public static int Main(string[] args)
    {
        Console.WriteLine("'nReflection.PropertyInfo");
        // Define a property.
        Myproperty Myproperty = new Myproperty();
        Console.Write("'nMyproperty.Caption = " + Myproperty.Caption);
        // Get the type and PropertyInfo.
        Type MyType = Type.GetType("Myproperty");
        PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
        // Get and display the attributes property.
        PropertyAttributes Myattributes = Mypropertyinfo.Attributes;
        Console.Write("'nPropertyAttributes - " + Myattributes.ToString());
        return 0;
    }
}

MSDN

public static bool PropertyReadOnlyAttributeValue(PropertyInfo property)
{
    ReadonlyAttribute attrib = Attribute.GetCustomAttribute(property, typeof(ReadOnlyAttribute));
    return attrib != null && attrib.IsReadOnly;
}
public static bool PropertyReadOnlyAttributeValue(Type type, string propertyName)
{
    return PropertyReadOnlyAttributeValue(type.GetProperty(propertyName));
}
public static bool PropertyReadOnlyAttributeValue(object instance, string propertyName)
{
    if (instance != null)
    {
        Type type = instance.GetType();
        return PropertyReadOnlyAttributeValue(type, propertyName);
    }
    return false;
}