属性上的自定义属性 – 获取属性的类型和值

我有以下自定义属性,可以应用于属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class IdentifierAttribute : Attribute { } 

例如:

 public class MyClass { [Identifier()] public string Name { get; set; } public int SomeNumber { get; set; } public string SomeOtherProperty { get; set; } } 

还有其他类,Identifier属性可以添加到不同类型的属性中:

 public class MyOtherClass { public string Name { get; set; } [Identifier()] public int SomeNumber { get; set; } public string SomeOtherProperty { get; set; } } 

然后我需要能够在我的消费类中获取这些信息。 例如:

 public class TestClass { public void GetIDForPassedInObject(T obj) { var type = obj.GetType(); //type.GetCustomAttributes(true)??? } } 

解决这个问题的最佳方法是什么? 我需要得到[Identifier()]字段的类型(int,string等)和实际值,显然是基于类型。

类似下面的东西,这将只使用它具有属性的第一个属性,当然你可以把它放在多个..

  public object GetIDForPassedInObject(T obj) { var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1); object ret = prop !=null ? prop.GetValue(obj, null) : null; return ret; } 
 public class TestClass { public void GetIDForPassedInObject(T obj) { PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); PropertyInfo IdProperty = (from PropertyInfo property in properties where property.GetCustomAttributes(typeof(Identifier), true).Length > 0 select property).First(); if(null == IdProperty) throw new ArgumentException("obj does not have Identifier."); Object propValue = IdProperty.GetValue(entity, null) } } 

有点晚了,但这是我为枚举做的事情(也可能是任何对象)并使用扩展获取描述属性值(这可能是任何属性的通用):

 public enum TransactionTypeEnum { [Description("Text here!")] DROP = 1, [Description("More text here!")] PICKUP = 2, ... } 

获得价值:

 var code = TransactionTypeEnum.DROP.ToCode(); 

扩展支持我的所有枚举:

 public static string ToCode(this TransactionTypeEnum val) { return GetCode(val); } public static string ToCode(this DockStatusEnum val) { return GetCode(val); } public static string ToCode(this TrailerStatusEnum val) { return GetCode(val); } public static string ToCode(this DockTrailerStatusEnum val) { return GetCode(val); } public static string ToCode(this EncodingType val) { return GetCode(val); } private static string GetCode(object val) { var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : string.Empty; }