1. Enum with string type?
The UK mentions such a problem in the various enumerations:
The member types of the enumeration are numeric, what are the ways to do a character-type enumeration?
enum colors : string{
red='#ff0000',
}
Before we start the discussion, I think it is necessary to find out another problem, the "#ff0000" in the code is not a character but a string, should be changed to "#ff0000", so the UK's problem is also smoothly changed to "want to do a string enumeration has any way."
Quite frankly,. NET does not support such a string enumeration. Also, not all numeric types can be the underlying type of an enumeration, the underlying type of an enumeration can only be an integer type, which means that one day you want to define an enumeration with the underlying type double, and you will receive a warning letter from the compiler.
The UK code does raise the requirement that colors is like an enumeration, but the value of its members is a string, so it is easy for us to have the question of whether we can simulate such an enumeration.
2. Is there a way to simulate it?
Before writing any code, let's first think about how we would use it if there was a Color class. Here are two uses I've come up with:
1// Code #01
2
3Color c1 = Color.Red;
4string s1 = (string)c1;
5Debug.Assert(s1 == "#FF0000");
6
7Color c2 = (Color)"#00FF00";
8Debug.Assert(c2 == Color.Green);
First, enumerations are initialized by their members rather than constructors, as in the third line of the code above. So, we should make the constructor private, simulate some of the enumeration members and expose it:
// Code #02
public class Color
{
private Color(string value)
{
m_Value = value;
}
private string m_Value;
public static readonly Color Red = new Color("#FF0000");
public static readonly Color Green = new Color("#00FF00");
public static readonly Color Blue = new Color("#0000FF");
}