简体   繁体   English

创建没有0值的C#Enum实例

[英]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. 我需要创建一个没有0值的Enum类的实例。 With a 0 value, next code works fine: 使用0值,下一个代码可以正常工作:

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. 如果我注释掉DUMMY,则创建实例将不再起作用。

I need to create an instance of an Enum class that hasn't got a 0 value. 我需要创建一个没有0值的Enum类的实例。

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 : 如果您无法声明类型的变量,并且需要以字符串形式访问该类型(如示例所示),请使用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. 当然,这两个选项都会为你提供一个实际上具有整数值0的实例,即使枚举没有声明一个。 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: 如果您希望它默认为您实际声明的值之一,则需要使用Reflection来查找它,例如:

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. 如果要阻止此FirstOrDefault ,请使用FirstOrDefault并检查null

It's a problem with your ObjectFactory class, because 这是ObjectFactory类的问题,因为

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

works fine and creates int 0. 工作正常并创建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. 枚举是每个定义的一个值字段,因此必须使用0数值初始化它。

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. 最佳做法是提供零值枚举成员 - 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/ms182149%28VS.80%29.aspx Is there any reason you don't want a zero valued member such as None? 你有什么理由不想要零价值的会员,如无?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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