C# 泛型 获得 Enum

  public static T GetEmum<T>(this JsonData json, string key) where T : Enum
    {
        T result = default;

        if (json != null && json.ContainsKey(key))
        {
            if (json[key].IsInt)
            {
                int.TryParse(json[key].ToString(), out int type);

                int index = 0;

                foreach (T value in Enum.GetValues(typeof(T)))
                {
                    if (type == index++)
                    {
                        result = value;
                        break;
                    }
                }
            }
            else if (json[key].IsString)
            {
                string type = json[key].ToString();

                foreach (T value in Enum.GetValues(typeof(T)))
                {
                    if (type == value.ToString())
                    {
                        result = value;
                        break;
                    }
                }
            }
        }

        return result;
    }
原文地址:https://www.cnblogs.com/Joke-crazy/p/12929340.html