阅读自定义属性

时间:2018-02-23 04:15:15

标签: c# attributes system.reflection

在我的下面的代码片段中,我无法理解为什么属性“XX”的“customAttribute”值始终为null。但它对于属性“X”工作正常。 有什么想法吗?

感谢。

System.Reflection.PropertyInfo[] props = myInp.GetProperties();
foreach (var prop in props)
{
  if (prop.Name == "XX")
  {
    var customAttribute = prop.GetCustomAttribute(typeof(CustomAttribute)) as CustomAttribute; //This is always null for XX                      
     }
}


    public class MyClass
    {

    [CustomAttribute(MyProp1 = true, MyProp2="test")]
    public bool X{ get ; set;}, 

    [CustomAttribute(MyProp1 = true)]   
    public MyEnum XX{ get ; set;}

    }


    public enum MyEnum
        {
            ABC = 0,
            XYZ = 1
        }


    public class CustomAttribute : Attribute
    {
        public bool MyProp1 { get; set; }
            public string MyProp2 { get; set; }

    }              

1 个答案:

答案 0 :(得分:0)

这对我来说很好用:

class Program
{
    static void Main(string[] args)
    {
        var myClassProps = typeof(MyClass).GetProperties();

        foreach (var prop in myClassProps.Where(p => p.Name == nameof(MyClass.XX)))
        {
            var attribs = prop.GetCustomAttributes(typeof(CustomAttribute), false);

            if (attribs.Length > 0)
            {
                var customAttrib = attribs[0] as CustomAttribute;

                //Do Something with it here
            }
        }
    }
}

public enum MyEnum
{
    ABC = 0,
    XYZ = 1
}


public class CustomAttribute : Attribute
{
    public bool MyProp1 { get; set; }
    public string MyProp2 { get; set; }
}

public class MyClass
{
    [Custom(MyProp1 = true, MyProp2 = "test")]
    public bool X { get; set; } 

    [Custom(MyProp1 = true)]
    public MyEnum XX { get; set; }
}

我不确定你从哪里得到PropertyInfo.GetCustomAttribute,我在PropertyInfo找不到该成员。