简体   繁体   English

使用反射读取属性的属性

[英]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. 在不知道Type名称的情况下,很难为您的案例编写代码。 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 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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