简体   繁体   中英

convert string property of list to enum

How can I convert my list Letter string property Size to an enum correctly?

Customer.Letter.Size is type string.

Customer.Letter[i].Size = (BusinessObjects.CONSTANTS.E_Letters)BusinessObjects.CONSTANTS.dict[Customer.Letter[i].Size];//i variable declared in an for loop

That is my enum:

public enum E_Size {
    small = 1,
    medium = 2,
    big = 3
}

Here my dictionary:

    public static Dictionary<string, E_Size> dict = new Dictionary<string, E_Size> {
        { "small", E_Size.small},
        { "medium", E_Size.medium},
        { "big", E_Size.big}
    };

Why not using standard Enum.Parse ?

  String source = "small"; 
  // E_Size.small 
  E_Size size = (E_Size) (Enum.Parse(typeof(E_Size), source));

Reverse conversion (from E_Size to String ) either

  E_Size source = E_Size.small;
  String result = source.ToString();

or

  E_Size source = E_Size.small;
  String result = Enum.GetName(typeof(E_Size), source);

转换为字符串,而不是枚举:

Customer.Letter[i].Size = BusinessObjects.CONSTANTS.dict[Customer.Letter[i].Size].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM