如何访问const或属性上的Description属性,即
public static class Group
{
[Description( "Specified parent-child relationship already exists." )]
public const int ParentChildRelationshipExists = 1;
[Description( "User is already a member of the group." )]
public const int UserExistsInGroup = 2;
}
或
public static class Group
{
[Description( "Specified parent-child relationship already exists." )]
public static int ParentChildRelationshipExists {
get { return 1; }
}
[Description( "User is already a member of the group." )]
public static int UserExistsInGroup {
get { return 2; }
}
}
在调用类中,我想访问Description属性,即
int x = Group.UserExistsInGroup;
string description = Group.UserExistsInGroup.GetDescription(); // or similar
我也对其他方法的想法持开放态度。
修改 我应该提到我在这里看到了一个例子: Do auto-implemented properties support attributes?
但是,我正在寻找一种方法来访问description属性,而不必在属性类型中输入字符串文字,即,我宁愿不这样做:
typeof(Group).GetProperty("UserExistsInGroup");
扩展方法的某些内容;类似于以下方法,它将通过扩展方法返回Enum上的Description属性:
public static String GetEnumDescription( this Enum obj )
{
try
{
System.Reflection.FieldInfo fieldInfo =
obj.GetType().GetField( obj.ToString() );
object[] attribArray = fieldInfo.GetCustomAttributes( false );
if (attribArray.Length > 0)
{
var attrib = attribArray[0] as DescriptionAttribute;
if( attrib != null )
return attrib.Description;
}
return obj.ToString();
}
catch( NullReferenceException ex )
{
return "Unknown";
}
}
答案 0 :(得分:20)
尝试以下
var property = typeof(Group).GetProperty("UserExistsInGroup");
var attribute = property.GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
var description = (DescriptionAttribute)attribute;
var text = description.Description;
答案 1 :(得分:4)
您可以致电MemberInfo.GetCustomAttributes()以获取Type
成员上定义的所有自定义属性。您可以通过以下操作获取该属性的MemberInfo
:
PropertyInfo prop = typeof(Group).GetProperty("UserExistsInGroup",
BindingFlags.Public | BindingFlags.Static);
答案 2 :(得分:2)
好的,我已经看过你的编辑了,我不确定你能用扩展方法做到这一点,因为他们会知道包含类的类型。
这听起来有些古怪,但是如何创建一个新的类“DescribedInt”,它会有一个隐式的强制转换操作符让你自动将它用作int?你几乎可以使用你描述的方式。你仍然会有一个描述,但是当你需要像Int一样使用它时,你不需要获得.Data属性......
例如:
private void ExampleUse()
{
int myvalue = Group.A; //see, no need to cast or say ".Data" - implicit cast
string text = Group.A.Description;
//用值来做事...... }
public static class Group
{
public static DescribedInt A = new DescribedInt(12, "some description");
public static DescribedInt B = new DescribedInt(88, "another description");
}
public class DescribedInt
{
public readonly int data;
public readonly string Description;
public DescribedInt(int data, string description)
{
this.data = data;
this.Description = description;
}
//automatic cast to int
public static implicit operator int(DescribedInt orig)
{
return orig.data;
}
//public DescribedInt(string description)
//{
// this.description = description;
//}
//if you ever need to go the "other way"
//public static implicit operator DescribedInt(int orig)
//{
// return new DescribedInt(orig, "");
//}
}
答案 3 :(得分:2)
这是我用来处理.NET中的自定义属性的辅助类
public class AttributeList : List<Attribute>
{
/// <summary>
/// Gets a list of custom attributes
/// </summary>
/// <param name="propertyInfo"></param>
/// <returns></returns>
public static AttributeList GetCustomAttributeList(ICustomAttributeProvider propertyInfo)
{
var result = new AttributeList();
result.AddRange(propertyInfo.GetCustomAttributes(false).Cast<Attribute>());
return result;
}
/// <summary>
/// Finds attribute in collection by its type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T FindAttribute<T>() where T : Attribute
{
return (T)Find(x => typeof(T).IsAssignableFrom(x.GetType()));
}
public bool IsAttributeSet<T>() where T : Attribute
{
return FindAttribute<T>() != null;
}
}
还为MsTest进行单元测试,显示如何使用此类
[TestClass]
public class AttributeListTest
{
private class TestAttrAttribute : Attribute
{
}
[TestAttr]
private class TestClass
{
}
[TestMethod]
public void Test()
{
var attributeList = AttributeList.GetCustomAttributeList(typeof (TestClass));
Assert.IsTrue(attributeList.IsAttributeSet<TestAttrAttribute>());
Assert.IsFalse(attributeList.IsAttributeSet<TestClassAttribute>());
Assert.IsInstanceOfType(attributeList.FindAttribute<TestAttrAttribute>(), typeof(TestAttrAttribute));
}
}
http://www.kozlenko.info/2010/02/02/getting-a-list-of-custom-attributes-in-net/