【发布时间】: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