How to give enum values that are having space

前端 未结 5 2013
走了就别回头了
走了就别回头了 2021-01-23 22:39

i have to create an enum that contains values that are having spaces

public enum MyEnum
        {
            My cart,
            Selected items,
            Bi         


        
相关标签:
5条回答
  • 2021-01-23 23:15

    I agree the use of DisplayText if you are following convention. But if you need different display value to represent the enum constant, then you could have a constructor passing that value.

    public enum MyEnum { My cart ("Cart"), Selected items("All Selected Items"), Bill("Payment");

    private String displayValue; 
    private MyEnum(String displayValue) {
    

    this.displayValue = displayValue; }
    public String displayText() { return this.displayValue; }

    }

    You can have a displayText method or a toString method which would return the displayValue

    0 讨论(0)
  • 2021-01-23 23:23

    As per the C# specification, "An enumerator may not contain white space in its name." (see http://msdn.microsoft.com/en-us/library/sbbt4032.aspx) Why do you need this?

    0 讨论(0)
  • 2021-01-23 23:25

    From enum (C# Reference)

    An enumerator may not contain white space in its name.

    0 讨论(0)
  • 2021-01-23 23:34

    Enum just cant have space! What do you need it for? If you need it simply for display purpose, you can stick with underscore and write an extension method for your enum so that you can ask for the display text by doing this (assuming your ext method is call DisplayText). Internally you just implement the DisplayText method to substitute "_" with space

    MyEnum.My_Cart.DisplayText();   // which return "My Cart"
    
    0 讨论(0)
  • 2021-01-23 23:39

    **

    enums can't have spaces in C#!" you say. Here is the way System.ComponentModel.DescriptionAttribute to add a more friendly description to the enum values. The example enum can be rewritten like **

    public enum DispatchTypes
        {
            Inspection = 1,
            LocalSale = 2,[Description("Local Sale")]
            ReProcessing=3,[Description("Re-Processing")]
            Shipment=4,
            Transfer=5
        }
    

    Hence it returns "LocalSale" or "ReProcessing", when we use .ToString()

    0 讨论(0)
提交回复
热议问题