C#枚举:可空或“未知”值? [英] C# Enums: Nullable or 'Unknown' Value?

查看:116
本文介绍了C#枚举:可空或“未知”值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个具有枚举成员的类,并且我想能够表示这个成员没有被定义的情况,哪个更好?

If I have a class with an enum member and I want to be able to represent situations where this member is not defined, which is it better?

a)使用可空类型在该类中声明成员为空。公开SomeEnum?

a) Declare the member as nullable in the class using nullable types. E.g.:

public SomeEnum? myEnum;

b)为枚举添加一个默认的'unknown'值。例如:

b) Add a default, 'unknown' value to the enumeration. E.g.:

public enum SomeEnum {
    Unknown,
    SomeValueA,
    SomeValueB,
    SomeValueC,
}

我无法真正看到任何主要的利弊办法;但是也许比其他人更喜欢一个?

I can't really see any major pros/cons either way; but perhaps one is preferable over the other?

推荐答案

绝对使用一个可空的值类型 - 这就是他们所要做的。它明确表示你的意图。这也意味着您可以使用 Enum.IsDefined (或等同于无约束旋律如果您想要通用类型的安全性)轻松确定特定值是否为真实值,而不必担心假。

Definitely use a nullable value type - that's what they're for. It explicitly states your intention. It also means you can use Enum.IsDefined (or the equivalent from Unconstrained Melody if you want generic type safety) to easily determine whether a particular value is a real value without worrying about the "fake" one too.

这篇关于C#枚举:可空或“未知”值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆