c# 获取枚举[description]

如何获取属性[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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容