Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中访问属性或常量的Description属性?_C#_.net_Attributes - Fatal编程技术网

如何在C#中访问属性或常量的Description属性?

如何在C#中访问属性或常量的Description属性?,c#,.net,attributes,C#,.net,Attributes,如何访问常量或属性的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." )]

如何访问常量或属性的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;

}
int x = Group.UserExistsInGroup;
string description = Group.UserExistsInGroup.GetDescription(); // or similar

在调用类中,我希望访问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;

}
int x = Group.UserExistsInGroup;
string description = Group.UserExistsInGroup.GetDescription(); // or similar
我对其他方法也持开放态度

编辑: 我应该提到,我在这里看到了一个示例:

但是,我正在寻找一种方法来访问description属性,而不必在属性类型中输入字符串文字,也就是说,我不希望这样做:

typeof(Group).GetProperty("UserExistsInGroup");
类似于扩展方法的东西;类似于以下方法,该方法将通过扩展方法返回枚举上的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";
    }
}
试试下面的方法

var property = typeof(Group).GetProperty("UserExistsInGroup");
var attribute = property.GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
var description = (DescriptionAttribute)attribute;
var text = description.Description;
您可以调用以获取在
类型的成员上定义的任何自定义属性。通过执行以下操作,可以获取属性的
MemberInfo

PropertyInfo prop = typeof(Group).GetProperty("UserExistsInGroup",
    BindingFlags.Public | BindingFlags.Static);

好的,我看过你们的编辑,我不确定你们能不能用扩展方法来做,因为它们是包含类类型的软件

这听起来有点奇怪,但是创建一个新的类a“DescribedInt”怎么样?它将有一个隐式cast操作符,让您自动将其用作int?你将能够使用你描述的几乎所有东西。您仍然有一个描述,但是当您需要像Int一样使用它时,您不需要获取.Data属性

例如:

//做一些有价值的事情。。。 }


下面是一个助手类,我正在使用它来处理.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;
    }
}

public class AttributeList:List

@JaredPar-对不起,我应该澄清一下,请查看我的编辑。我知道这是一个非常古老的答案,但不应该是
var description=(DescriptionAttribute)属性?我认为这是不可能的,至少在使用属性时是这样。您需要获取属性的PropertyInfo,唯一的方法是通过属性名称搜索它。@Ilya-这可能是一个可行的选择。明天我会仔细看看。谢谢回复您的编辑:将此视为安全获取属性信息的一种方式。我在这里使用的代码是:var attributeList=attributeList.GetCustomAttributeList(MethodInfo.GetCurrentMethod());var attribute=attributeList.FindAttribute().Description;
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;
    }
}
[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));
    }
}