Enum的C#显式初始化 [英] C# explicit initialization for Enum
问题描述
我有以下声明:
private Enum _statusValue;
我真正想说的是:
private Enum _statusValue = 0;
即使我知道这是多余的。只是我想明确指定初始化。
even though I know it's redundant. It's just that I like to explicitly specify the initialization.
但这是不允许的。
是否有一些简单的方法来指定这种声明的初始化?
Is there some simple way of specifying the initialization on this kind of declaration?
编辑-让我尝试再次。
这里是我正在做的人为设计/简化示例。
Here is a contrived / simplified example of what I'm doing.
using System;
namespace EnumTesting
{
public enum EFixedPhoneUsability
{
UnknownValue, // Should not occur?
IsUsable, // User is near the telephone
NotUsable, // User not near the telephone
BeingUsed, // Busy
DoNotDisturb, // This is phone physical state, not user attitude
CallsForwarded // This is phone physical state
}
public enum EMobilePhoneConnectivity
{
UnknownValue, // Should not occur?
OnNetIdle, // I.e., usable
OnNetBusy, // Being used
NoConnection // Turned off, in elevator or tunnel or far from civilization
}
public class Program
{
public Enum StatusValue;
static void Main(string[] args)
{
Program p = new Program();
p.StatusValue = EMobilePhoneConnectivity.NoConnection;
int i = (int) (EMobilePhoneConnectivity) p.StatusValue;
p.StatusValue = EFixedPhoneUsability.DoNotDisturb;
i = (int) (EFixedPhoneUsability) p.StatusValue;
}
}
}
所以我的问题是
public Enum StatusValue;
第二编辑:
没关系,
How to convert from System.Enum to base integer?
关键词,其中让我意识到我做错了什么,是这样的:枚举是值类型(并且内部仅由整数常量表示),而System.Enum是引用类型。
The key phrase, which made me realize what I was doing wrong, is this: "enumerations are value types (and internally represented only by integer constants) while System.Enum is a reference type".
所以我不想这样说:
private Enum _statusValue = 0;
我要说的是,这是完全正确的:
I want to say this, which is perfectly valid:
private Enum _statusValue = null;
感谢那些尝试提供帮助的人。
Thank you to those who tried to help.
推荐答案
我的问题基本上是错误的。我曾经错误地认为Enum(像枚举)是一种值类型,但实际上是引用类型。
My question was basically in error. I had mistakenly thought Enum (like enums) was a value type, but it is actually a reference type.
所以我不想这么说:
private Enum _statusValue = 0;
我要说的是,这是完全正确的:
I want to say this, which is perfectly valid:
private Enum _statusValue = null;
感谢那些尝试提供帮助的人。
Thank you to those who tried to help.
这篇关于Enum的C#显式初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!