C# 公用方法总结--枚举

1:枚举--根据value找text

public enum State
{
    全新 = 0,
    已维修 = 1,
    已报废 = 2
}
public static string CheckEnum(object checkedValue)
{
    try
    {
        return Enum.Parse(typeof(T), checkedValue.ToString().Trim()).ToString();
    }
    catch
    {
        return string.Empty;
    }
}

调用方法:CheckEnum(0);-->输出:全新 

2:枚举--获取枚举作为下拉数据

public class Tree
{
    public int value { get; set; }
    public string text { get; set; }
}
public static void BindEnum(List DataList)
{
    Type enumSource = typeof(T);
    foreach (int itemValue in Enum.GetValues(enumSource))
    {
        DataList.Add(new Tree { text = Enum.GetName(enumSource, itemValue), value = itemValue });
    }
}

调用方法:BindEnum(TreeList);-->输出:List 

3:特殊枚举--双字符串

public class Type
{
    public const string A类 = "A";
    public const string B类 = "B";
}
public static string CheckFields(object checkedValue, T obj)
{
    try
    {
        string returns = "";
        var type = typeof(T);
        foreach (FieldInfo field in type.GetFields())
        {
            if (checkedValue.ToString() == field.GetValue(obj).ToString())
            {
                returns = field.Name;
                break;
            }
        }
        return returns;
    }
    catch
    {
        return string.Empty;
    }
}

调用方法:CheckFields("A", new Type());-->输出:A类

你可能感兴趣的:(C#,c#)