C 列舉值 (二) 多屬性 操作

2022-01-29 21:14:30 字數 2107 閱讀 6515

很多時候,我們的列舉值可能需要中英文,

那麼可以使用下面的方法:

下面這個類,包含2部分。

1 basedescriptionattribute特性的過載

2 列舉的操作類 enumoperate

namespace testmvc.lang

public basedescriptionattribute(string descriptioncn, string descriptionen)

: base(descriptioncn)

private string descriptionen;

public string descriptionen

set }}

public static class enumoperate

fieldinfo field = type.getfield(name);

basedescriptionattribute attribute = attribute.getcustomattribute(field, typeof(basedescriptionattribute)) as basedescriptionattribute;

if (attribute == null && nameinstead == true)

else

}/// /// 擴充套件方法,獲得列舉的description

///

/// 列舉值

/// 當列舉值沒有定義descriptionattribute,是否使用列舉名代替,預設是使用

/// 列舉的description

public static string getdescription(this enum value, boolean nameinstead = true)

fieldinfo field = type.getfield(name);

descriptionattribute attribute = attribute.getcustomattribute(field, typeof(descriptionattribute)) as descriptionattribute;

if (attribute == null && nameinstead == true)

return attribute == null ? null : attribute.description;

}/// /// 把列舉轉換為鍵值對集合

/// 列舉轉換為鍵值對集合

/// dictionarydic = enumutil.enumtodictionary(typeof(season), e => e.getdescription());

///

/// 列舉型別

/// 獲得值得文字

/// 以列舉值為key,列舉文字為value的鍵值對集合

public static dictionaryenumtodictionary(type enumtype, funcgettext)

dictionaryenumdic = new dictionary();

array enumvalues = enum.getvalues(enumtype);

foreach (enum enumvalue in enumvalues)

return enumdic;

}/// /// 獲取列舉的相關資訊

///

/// 列舉的型別

///

public static listgetenumitems(type e)

return itemlist;

}public class enumitem

public string enumvalue

public string descriptioncn

public string descriptionen }}

}

列舉類:

namespace testmvc.lang}}

前台測試結果:

c 對xml多屬性節點的增加,刪除,修改操作原始碼

別人的 可以借鑑一下,先保留明天上公司摘抄一下。using system using system.collections using system.componentmodel using system.data using system.drawing using system.web usin...

在C 中如何讀取列舉值的描述屬性

在c 中,有時候我們需要讀取列舉值的描述屬性,也就是說這個列舉值代表了什麼意思。比如本文中列舉值 chinese 我們希望知道它代表意思的說明 即 中文 有下面的列舉 1 2 3 4 5 6 publicenumenumlanugage 我們要獲取的就是 chinese 中的說明文字 中文 1 2 ...

在C 中如何讀取列舉值的描述屬性

在c 中,有時候我們需要讀取列舉值的描述屬性,也就是說這個列舉值代表了什麼意思。比如本文中列舉值 chinese 我們希望知道它代表意思的說明 即 中文 有下面的列舉 public enum enumlanugage 我們要獲取的就是 chinese 中的說明文字 中文 public static ...