简体   繁体   中英

Reading attribute of a property using reflection

I need to read the attribute of a property using reflection

For example I get the following :

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

i want to get the " read only "value of this property using reflection can anybody help

It's difficult to write the code for your case without knowing the Type name. Hope below example helps.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM