简体   繁体   中英

Creating an instance of an C# Enum with no 0 value

I need to create an instance of an Enum class that hasn't got a 0 value. With a 0 value, next code works fine:

ObjectFactory.CreateInstance("Edu3.DTOModel.Schedule.ScheduleStateEnum");

Enum:

namespace Edu3.DTOModel.Schedule
{
    public enum ScheduleStateEnum
    {
        DUMMY = 0,
        Draft = 1,
        Published = 2,
        Archived = 3
    }
}

If I comment out DUMMY, Creating the instance doesn't work anymore.

I need to create an instance of an Enum class that hasn't got a 0 value.

Assuming an enum like this:

public enum ScheduleStateEnum
{
    Draft = 1,
    Published = 2,
    Archived = 3
}

you can create an instance like this:

ScheduleStateEnum myState = 0;

If you cannot declare a variable of the type and you need to access the type as a string (as in your example), use Activator.CreateInstance :

var myState = Activator.CreateInstance(Type.GetType(
                  "Edu3.DTOModel.Schedule.ScheduleStateEnum"));

Of course, both of these options will give you an instance that actually has the integer value 0 , even if the enum doesn't declare one. If you want it to default to one of the values you have actually declared, you need to use Reflection to find it, for example:

var myState = Type.GetType("Edu3.DTOModel.Schedule.ScheduleStateEnum")
                  .GetFields(BindingFlags.Static | BindingFlags.Public)
                  .First()
                  .GetValue(null);

This will crash for enums that have no values at all defined. Use FirstOrDefault and check for null if you want to prevent this.

It's a problem with your ObjectFactory class, because

Activator.CreateInstance(typeof(Edu3.DTOModel.Schedule.ScheduleStateEnum))

works fine and creates int 0.

Actually it is not possible. Enum is per definition a value field, so it has to ahve a way to initialize it with a 0 numerical value.

It is best practice to provide a zero valued enum member - see http://msdn.microsoft.com/en-us/library/ms182149%28VS.80%29.aspx for details. Is there any reason you don't want a zero valued member such as None?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM