创建不包含 0 值的 C# 枚举实例
我需要创建一个没有 0 值的 Enum 类的实例。使用 0 值时,下一个代码可以正常工作:
ObjectFactory.CreateInstance("Edu3.DTOModel.Schedule.ScheduleStateEnum");
Enum:
namespace Edu3.DTOModel.Schedule
{
public enum ScheduleStateEnum
{
DUMMY = 0,
Draft = 1,
Published = 2,
Archived = 3
}
}
如果我注释掉 DUMMY,则创建实例将不再起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设像这样的枚举:
您可以创建这样的实例:
如果您无法声明该类型的变量并且需要以字符串形式访问该类型(如您的示例中所示),请使用 Activator.CreateInstance:
当然,这两个选项都会为您提供一个实际上具有整数值
0
的实例,即使枚举没有声明一个。如果您希望它默认为您实际声明的值之一,则需要使用反射来查找它,例如:对于根本没有定义值的枚举,这将会崩溃。如果您想防止这种情况,请使用 FirstOrDefault 并检查
null
。Assuming an enum like this:
you can create an instance like this:
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
: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:This will crash for enums that have no values at all defined. Use
FirstOrDefault
and check fornull
if you want to prevent this.这是您的 ObjectFactory 类的问题,因为
Activator.CreateInstance(typeof(Edu3.DTOModel.Schedule.ScheduleStateEnum))
工作正常并创建 int 0。
It's a problem with your ObjectFactory class, because
Activator.CreateInstance(typeof(Edu3.DTOModel.Schedule.ScheduleStateEnum))
works fine and creates int 0.
事实上这是不可能的。根据定义,枚举是一个值字段,因此它必须有一种方法用 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.
最佳做法是提供零值枚举成员 - 请参阅 http://msdn.microsoft.com/en-us/library/ms182149%28VS.80%29.aspx 了解详细信息。您是否有任何理由不想要零值成员(例如 None)?
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?