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

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

问题描述

如果我有一个带有 enum 成员的类,并且我希望能够表示未定义该成员的情况,哪个更好?

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) 使用可为空类型在类中将该成员声明为可为空的.例如:

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

public SomeEnum? myEnum;

b) 为枚举添加一个默认的未知"值.例如:

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天全站免登陆