有了更新的例子:
public class MyTest
{
public static int A =1;
}
與用法:
int a = MyTest.A;
這不如何枚舉看。枚舉看起來更像(評論是,我們從一個真正的枚舉不同的地方):
public struct MyTest /* Of course, this isn't correct, because we'll inherit from System.ValueType. An enum should inherit from System.Enum */
{
private int _value; /* Should be marked to be treated specially */
private MyTest(int value) /* Doesn't need to exist, since there's some CLR fiddling */
{
_value = value;
}
public static explicit operator int(MyTest value) /* CLR provides conversions automatically */
{
return value._value;
}
public static explicit operator MyTest(int value) /* CLR provides conversions automatically */
{
return new MyTest(value);
}
public static readonly MyTest A = new MyTest(1); /* Should be const, not readonly, but we can't do a const of a custom type in C#. Also, is magically implicitly converted without calling a constructor */
public static readonly MyTest B = new MyTest(2); /* Ditto */
}
是的,你可以輕鬆到達「底層」 int值,但A
和B
值仍強烈鍵入爲MyTest
。這確保你不會意外地在他們不合適的地方使用它們。
http://stackoverflow.com/questions/97391/how-to-get-the-underlying-value-of-an-enum – 2kay 2012-08-15 12:00:42
這是一個設計選擇。我猜C#發明者認爲它更安全和/或更具可讀性。 – 2012-08-15 12:01:57
這種情況會有什麼令人信服的理由? – 2012-08-15 12:02:46