使用反射读取属性的属性

时间:2011-08-29 23:33:42

标签: c# .net reflection c#-4.0

我需要使用反射

来读取属性的属性

例如,我得到以下内容:

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

我想使用反射获取此属性的“只读”值 任何人都可以帮忙

2 个答案:

答案 0 :(得分:0)

如果不知道类型名称,很难为您的案例编写代码。希望以下示例有所帮助。

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

答案 1 :(得分:0)

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;
}