C#Enum枚举显示中文描述(DescriptionAttrib
2023-09-17 本文已影响0人
好怕怕
主要依靠DescriptionAttribute特性实现
using System;
using System.ComponentModel;
using UnityEngine;
public class EnumTest : MonoBehaviour
{
public enum EResType
{
[Description("编译器")]
Editor = 1,
[Description("本地")]
Res = 2,
[Description("运行时")]
AB = 3,
}
void Awake()
{
foreach (var var in Enum.GetValues(typeof(EResType)))
{
string desc = GetDescription((EResType)var);
Debug.Log(desc);
}
}
string GetDescription(Enum val)
{
var field = val.GetType().GetField(val.ToString());
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
}