【问题标题】:Read override property attribute读取覆盖属性属性
【发布时间】:2014-03-05 08:37:27
【问题描述】:

我在类中有重写的属性,并想读取自定义属性值,但它不起作用。谁能解释它为什么不起作用以及如何解决这个问题?

    public class Validator
    {


        [Serializable]
        public class CollectionAttribute : Attribute
        {
            public virtual string[] Data { get; set; }
            public string Default;
        }
}

 class Helpers
    {

        public static MemberInfo GetMemberInfo<T, TU>(Expression<Func<T, TU>> expression)
        {
            var member = expression.Body as MemberExpression;
            if (member != null)
                return member.Member;

            throw new ArgumentException("Expression is not a member access", "expression");
        }

        public static string GetName<T, TU>(Expression<Func<T, TU>> expression)
        {
            return GetMemberInfo(expression).Name;
        }

        public static string GetCollection<T, TU>(Expression<Func<T, TU>> expression)
        {
            var attribute = (Validator.CollectionAttribute[])GetMemberInfo(expression).GetCustomAttributes(typeof(Validator.CollectionAttribute), true);
            return string.Join(",", attribute[0].Data); 
        }
    }

不工作。

 public class TestClass:TestBaseClass
    {
        [Validator.Collection(Data = new[] { "doc", "docx", "dot", "dotx", "wpd", "wps", "wri" })]
        public override string InputFormat { get; set; }
    }

    public class TestBaseClass
    {
        public virtual string InputFormat { get; set; }
    }

Helpers.GetCollection((TestClass p) => p.InputFormat)
//The attribute variable in GetCollection method always null. It seems code looks for atribute in Base class.

工作正常。

 public class TestClass
    {
        [Validator.Collection(Data = new[] { "doc", "docx", "dot", "dotx", "wpd", "wps", "wri" })]
        public override string InputFormat { get; set; }
    }

Helpers.GetCollection((TestClass p) => p.InputFormat)

【问题讨论】:

    标签: c# reflection attributes custom-attributes


    【解决方案1】:

    InputFormat 的声明类型是 TestBaseClass,它没有该属性。而返回的PropertyInfo是声明类型,而不是参数的实际类型。

    您需要做的是检索表达式参数的实际类型,然后返回该类型的PropertyInfo

    public static MemberInfo GetMemberInfo<T, TU>(Expression<Func<T, TU>> expression)
    {
        var member = expression.Body as MemberExpression;
        if (member != null)
        {
            // Getting the parameter's actual type, and retrieving the PropertyInfo for that type.
            return expression.Parameters.First().Type.GetProperty(member.Member.Name);
        }
    
        throw new ArgumentException("Expression is not a member access", "expression");
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 2011-11-06
      • 1970-01-01
      • 2013-07-19
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多