问题描述
如何访问 const 或属性上的 Description 属性,即,
How do you access the Description property on either a const or a property, i.e.,
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 属性,即,
In the calling class I'd like to access the Description property, i.e.,
int x = Group.UserExistsInGroup;
string description = Group.UserExistsInGroup.GetDescription(); // or similar
我也对其他方法的想法持开放态度.
I'm open to ideas to other methodologies as well.
我应该提到我已经看到这里提供的一个例子:自动实现的属性是否支持属性?
I should have mentioned that I've seen an example provided here: Do auto-implemented properties support attributes?
但是,我正在寻找一种无需在属性类型中输入字符串文字即可访问描述属性的方法,即,我宁愿不这样做:
However, I'm looking for a method to access the description attribute without having to enter a string literal into the property type, i.e., I'd rather not do this:
typeof(Group).GetProperty("UserExistsInGroup");
类似于扩展方法的东西;类似于以下方法,它将通过扩展方法返回 Enum 上的 Description 属性:
Something along the lines of an Extension Method; similar to the following method that will return the Description attribute on an Enum via an Extension Method:
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";
}
}
推荐答案
您可以调用MemberInfo.GetCustomAttributes() 以获取在 Type
的成员上定义的任何自定义属性.您可以通过执行以下操作获取属性的 MemberInfo
:
You can call MemberInfo.GetCustomAttributes() to get any custom attributes defined on a member of a Type
. You can get the MemberInfo
for the property by doing something like this:
PropertyInfo prop = typeof(Group).GetProperty("UserExistsInGroup",
BindingFlags.Public | BindingFlags.Static);
这篇关于如何在 C# 中访问属性或 const 的描述属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!