通用的方法獲取列舉內各值的描述

2021-05-24 00:24:59 字數 1083 閱讀 1420

1.定義列舉時直接用中文

由於vs對中文支援的很不錯,所以很多程式設計師都採用了此方案.

缺點:1.不適合多語言 2.感覺不太完美,畢竟大部分程式設計師大部分**都使用英文

2.利用自定義屬性定義列舉值的描述(大尾巴狼

首先多謝兩位給我的提示,發現在上個

版本現在解決方案如下:

列舉定義:

[enumdescription("訂單、訂單中的產品、產品項的狀態。")]

public enum orderstateenum

**訪問:

0、獲得列舉型別的文字描述

stringtxt = enumdescription.getenumtext(typeof(orderstateenum));

1、獲得某個列舉值的文字描述:

string txt = enumdescription.getfieldtext(orderstateenum.processing)

2、獲得列舉中各個欄位的定義陣列:

enumdescription des = enumdescription.getfieldtexts(typeof(orderstateenum))

如果需要排序,通過他的另乙個過載public static enumdescription getfieldtexts( type enumtype, sorttype sorttype )

3、繫結到下拉框:

combobox1.datasource = enumdescription.getfieldtexts(typeof(orderstateenum));

combobox1.valuemember = "enumvalue";

combobox1.displaymember = "enumdisplaytext";

combobox1.selectedvalue = (int)orderstateenum.finished;  //選中值

從列舉值獲取對應的文字描述

有時列舉值在顯示時,需要顯示列舉值對應的文字串。一種方案是在呼叫的地方使用switch或者if來判斷列舉值,然後賦給不同的文字串,但這樣一來,如果有較多的地方都用到的時候就會比較麻煩。當然有人說,這種情況下,可以針對這種列舉值封裝乙個方法,然後來呼叫。那如果有多個列舉型別都有這樣的需求呢?有沒有什麼...

c 列舉的定義,列舉的用法,獲取列舉值

1.定義列舉型別 public enum test 2.獲取列舉值 public void enumsaction var g item.tostring 男 女 c typeof 和 gettype 區是什麼?1 typeof x 中的x,必須是具體的類名 型別 名稱等,不可以是變數名稱。2 ge...

c 列舉的定義,列舉的用法,獲取列舉值

1.定義列舉型別 public enum test 2.獲取列舉值 public void enumsaction var g item.tostring 男 女 對於typeof的解釋 c typeof 和 gettype 區是什麼?1 typeof x 中的x,必須是具體的類名 型別名稱等,不可...