我正在创建自定义属性。我将在多个类(class)中使用它:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class Display : System.Attribute
{
public string Name { get; set; }
public string Internal { get; set; }
}
public class Class1
{
[Display(Name = "ID")]
public int ID { get; set; }
[Display(Name = "Name")]
public string Title { get; set; }
}
public class Class2
{
[Display(Name = "ID")]
public int ID { get; set; }
[Display(Name = "Name")]
public string Title { get; set; }
}
这里工作正常,但我想让它尽可能通用,就像 MVC 示例一样:
Class1 class1 = new Class1();
class1.Title.DisplayName () / / returns the value "Name"
我唯一能做的就是为我的属性生成一个循环,但我需要通知我的 typeof Class1
foreach (var prop in typeof(Class1).GetProperties())
{
var attrs = (Display[])prop.GetCustomAttributes(typeof(Display), false);
foreach (var attr in attrs)
{
Console.WriteLine("{0}: {1}", prop.Name, attr.Name);
}
}
有什么办法可以按照我想要的方式去做吗?
最佳答案
你不能完全按照你所展示的那样做,因为 class1.Title
是一个计算结果为字符串的表达式。您正在查找有关 Title
属性的元数据。您可以使用表达式树让您写出接近的东西。这是一个简短的帮助程序类,它从表达式树中的属性中提取属性值:
public static class PropertyHelper
{
public static string GetDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
Expression expression;
if (propertyExpression.Body.NodeType == ExpressionType.Convert)
{
expression = ((UnaryExpression)propertyExpression.Body).Operand;
}
else
{
expression = propertyExpression.Body;
}
if (expression.NodeType != ExpressionType.MemberAccess)
{
throw new ArgumentException("Must be a property expression.", "propertyExpression");
}
var me = (MemberExpression)expression;
var member = me.Member;
var att = member.GetCustomAttributes(typeof(DisplayAttribute), false).OfType<DisplayAttribute>().FirstOrDefault();
if (att != null)
{
return att.Name;
}
else
{
// No attribute found, just use the actual name.
return member.Name;
}
}
public static string GetDisplayName<T>(this T target, Expression<Func<T, object>> propertyExpression)
{
return GetDisplayName<T>(propertyExpression);
}
}
下面是一些示例用法。请注意,您实际上什至不需要实例来获取此元数据,但我包含了一个可能很方便的扩展方法。
public static void Main(string[] args)
{
Class1 class1 = new Class1();
Console.WriteLine(class1.GetDisplayName(c => c.Title));
Console.WriteLine(PropertyHelper.GetDisplayName<Class1>(c => c.Title));
}
关于c# - 获取通用的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20342041/