Can enums contain strings? [duplicate]
How can I declare an enum
that has stri开发者_开发技巧ngs for values?
private enum breakout {
page = "String1",
column = "String2",
pagenames = "String3",
row = "String4"
}
No they cannot. They are limited to numeric values of the underlying enum type.
You can however get similar behavior via a helper method
public static string GetStringVersion(breakout value) {
switch (value) {
case breakout.page: return "String1";
case breakout.column: return "String2";
case breakout.pagenames: return "String3";
case breakout.row: return "String4";
default: return "Bad enum value";
}
}
As others have said, no you cannot.
You can do static classes like so:
internal static class Breakout {
public static readonly string page="String1";
public static readonly string column="String2";
public static readonly string pagenames="String3";
public static readonly string row="String4";
// Or you could initialize in static constructor
static Breakout() {
//row = string.Format("String{0}", 4);
}
}
Or
internal static class Breakout {
public const string page="String1";
public const string column="String2";
public const string pagenames="String3";
public const string row="String4";
}
Using readonly, you can actually assign the value in a static constructor. When using const, it must be a fixed string.
Or assign a DescriptionAttribute to enum values, like here.
No, but you can get the enum's value as a string:
Enum.ToString Method
private enum Breakout {
page,
column,
pagenames,
row
}
Breakout b = Breakout.page;
String s = b.ToString(); // "page"
An enum has integer as underlying type by default, which is also stated here on msdn.
Maybe Enum.GetName()/Enum.GetNames()
can be helpful for you.
You can create a dictionary of enums.
public enum OrderType
{
ASC,
DESC
}
public class MyClass
{
private Dictionary<OrderType, string> MyDictionary= new Dictionary<OrderType, string>()
{
{OrderType.ASC, ""},
{OrderType.DESC, ""},
};
}
精彩评论