开发者

C# explicit initialization for Enum

I have the following statement:

private Enum _statusValue;

What I'd really like to say is:

private Enum _statusValue = 0;

even though I know it's redundant. It's just that I like to explicitly specify the initia开发者_如何转开发lization.

But that is not allowed.

Is there some simple way of specifying the initialization on this kind of declaration?

EDIT - Let me try again.

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;
      }
   }
}

So my question is, can I add a generic initializer to this statement?

      public Enum StatusValue;

SECOND EDIT:

Never mind, I have discovered the error of my ways, thanks to this posting:

How to convert from System.Enum to base integer?

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".

So I do not want to say this:

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.


You could always declare your Enum slightly differently and add a default state (which is actually suggested by Microsoft):

public enum MyEnum
{
    Default = 0,
    One = 1, 
    Two = 2
}

Or simply (automatic numbering starts at 0):

public enum MyEnum
{
    Default,
    One,
    Two
}

Which would allow you to do the following:

private MyEnum _enum = MyEnum.Default;


My question was basically in error. I had mistakenly thought Enum (like enums) was a value type, but it is actually a reference type.

So I do not want to say this:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜