c# 获取枚举[description]

作者: ysl176 | 来源:发表于2016-01-29 10:42 被阅读2145次

    如何获取属性[Describtion]信息

    1 可以 通过:

    using UnityEngine;

    using System.Collections;

    using System.ComponentModel;

    using System.Reflection;

    public enum MyEnum

    {

    name1 = 1 ,

    [Description("Here is another")]

    HereIsAnother = 2,

    [Description("Last -- -- one")]

    LastOne = 3

    }

    public class EnumTest : MonoBehaviour {

    void Start () {

    Debug.Log(GetEnumDescription(MyEnum.LastOne));//通过枚举值获取值。

    int value = 2 ;

    Debug.Log(GetEnumDescription((MyEnum)value));//What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In //other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?可以 通过数字获取该表述。

    //The default underlying data type for anenumin C# is anint, you can just cast it. 在c#下 默认是潜在值是 int .}

    public static string GetEnumDescription(MyEnum value)

    {

    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =

    (DescriptionAttribute[])fi.GetCustomAttributes(

    typeof(DescriptionAttribute),

    false);

    if (attributes != null &&

    attributes.Length > 0)

    return attributes[0].Description;

    else

    return value.ToString();

    }

    }

    Debug.Log() ;  Last -- -- one

    Debug.Log(); Here is another

    相关文章

      网友评论

        本文标题:c# 获取枚举[description]

        本文链接:https://www.haomeiwen.com/subject/bmyjkttx.html