简体   繁体   中英

How to use ? character in an enum

I work in C#, Visual Studio '05... In my enum, how can I use the '?' character? My enum is below:

public enum Questions
{
    How_old_are_you?_= 0,//How to set the ? character 
    What_is_your_name= 1
}

After I add the '?' character there are some errors.

? isn't a valid character in a C# identifier (including enum values). I strongly suggest you use something like:

public enum Question
{
    [Description("How old are you?")]
    Age,

    [Description("What is your name?")]
    Name
}

Or have a map or a resource file etc - just don't try to make the name of the enum into a natural language description.

EDIT: For reference, if you want to get at the Description from code, here's how to do it (thanks Christian Hayter ):

((DescriptionAttribute) Attribute.GetCustomAttribute(
    typeof(Question).GetField("Age", BindingFlags.Public | BindingFlags.Static), 
        typeof(DescriptionAttribute), false)
).Description;

You can't. ? is an operator, so a sequence of characters containing it is not a valid identifier.

You can not use question marks in the enum identifiers. The identifiers in an enumeration follows the same rules as other identifiers.

You can use the @ character to use reserved keywords as identifiers, but you still can't use characters that are not allowed in an identifier.

You can add q after the question to make it descriptive. Ex:

  How_old_are_you_q= 0,        //Replace ? with q
    What_is_your_name_q= 1

You can tag your Enum items with underscore characters, which are allowed in Enum , and replace them for display.

Eg Binding an Enum to a ComboBox , say, replacing first "__" with "?", then "_" with space Enum item How_old_are_you__ becomes ComboBox item "How old are you?"

I use this when I want to stick with Enum over other options. It works well for partially loading Enum items into lists and display controls as well.

Another possible solution could be a mix between an enum and a dictionary :

public enum Question
{
  Age,
  Name
}

...

Dictionary<Question,string> Questions = new Dictionary<Question,string>();

Questions.Add(Question.Age,  "How old are you ?");
Questions.Add(Question.Name, "What is your name ?");

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