C# 中的 Tribool 实现
我正在尝试使用 http:// 实现 Tribool 类型www.boost.org/doc/libs/1_41_0/doc/html/tribool.html 作为参考。
我使用结构体,因为它是原始类型并且不应该是可扩展的。我知道 Tribool 有 3 种类型——True、False 和 Unknown,默认构造函数应该提供 False Tribool。我的问题是,我应该将 True、False 和 Unknown 设置为什么数据类型?现在我有:
struct Tribool
{
//True, False, and Unknown public constants
public static readonly Tribool TRUE, FALSE, UNKNOWN;
//Constructors
public Tribool()
{
Tribool = FALSE; //use ValueType instead?
}
但我不确定这是否正确,因为看起来我只是将一个 Tribool 设置为另一个 Tribool。我应该使用 ValueType 吗?当我在 VS 中输入时,它就弹出了,听起来很合理,但我无法从 Google 找到很多关于它的信息。
此外,Tribool 需要能够使用常规布尔值进行操作,这意味着需要重载“true”和“false”。这是否需要操作员重载?或者它应该只是一个返回布尔值的方法?
提前致谢!
编辑:抱歉,我应该提到这是一项作业。所以我不能使用布尔值,尽管正如你们许多人指出的那样,它更实用。
I'm trying to implement a Tribool type using http://www.boost.org/doc/libs/1_41_0/doc/html/tribool.html as reference.
I'm using a struct since it's a primitive type and shouldn't be extendable. I know there are 3 types of Tribools---True, False, and Unknown, and the default constructor should provide a False Tribool. My question is, what data type do I set True, False and Unknown to? Right now I have:
struct Tribool
{
//True, False, and Unknown public constants
public static readonly Tribool TRUE, FALSE, UNKNOWN;
//Constructors
public Tribool()
{
Tribool = FALSE; //use ValueType instead?
}
but I'm not sure if that's correct, since it looks like I'm just setting a Tribool to another Tribool. Should I use ValueType instead? It popped up when I was typing in VS, and it sounds sensible, but I wasn't able to find a lot of information on it from Google.
Also, the Tribool needs to be able to operate with regular bools, which means "true" and "false" need to be overloaded. Would this require an operator overload? Or should it just be a method that returns a bool?
Thanks in advance!
Edit: Sorry, I should have mentioned this was for an assignment. So I can't use bools even though it's a lot more practical as many of you have pointed out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
完毕。那个呢?特别是,C# 编译器将提供“提升”运算符来为您映射到
bool
。但可以说,它可能比一个bool
或单个枚举稍微大。注意:不要使用
ValueType
,因为这实际上是一个装箱操作。如果您不能使用
bool?
(即您想从头开始实现),我会将其映射到enum
(可能 一个byte
枚举,但我通常默认为int
):done. That do? In particular, the C# compiler will provide the "lifted" operators to map to
bool
for you. Arguably, though, it might be slightly larger than just abool
or single enum.Note: don't use
ValueType
, as this would actually be a boxing operation.If you couldn't use
bool?
(i.e. you wanted to implement from scratch) I would map it to anenum
(possibly abyte
enum, but I'd default toint
as normal):为什么不直接使用
bool?
这是一个可为空的布尔值?Why not just use
bool?
which is a nullable boolean?Nullable
有什么问题吗?What's wrong with
Nullable<bool>
?