为什么要重载true和false而不是定义bool运算符? [英] Why overload true and false instead of defining bool operator?

查看:183
本文介绍了为什么要重载true和false而不是定义bool运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关C#中对true和false进行重载的信息,我想我了解这与定义bool运算符之间的基本区别.我周围看到的示例是这样的:

public static bool operator true(Foo foo) {
  return (foo.PropA > 0);
}
public static bool operator false(Foo foo) {
  return (foo.PropA <= 0);
}

对我来说,这等于说:

public static implicit operator bool(Foo foo) {
  return (foo.PropA > 0);
}

据我所知,区别在于,通过分别定义true和false,您可以拥有一个既是true还是false的对象,或者不是true也不是false的对象:

public static bool operator true(Foo foo) { return true; }
public static bool operator false(Foo foo) { return true; }
//or
public static bool operator true(Foo foo) { return false; }
public static bool operator false(Foo foo) { return false; }

我确定允许这样做是有原因的,但我只是想不出它是什么.对我来说,如果您希望将一个对象转换为true或false,那么一个布尔运算符最有意义.

任何人都可以给我一种以其他方式有意义的方案吗?

谢谢

解决方案

文档说,重载truefalse旨在支持(可为空)数据库类型(是/否,是/否,0/1等).

当然,与任何运算符一样,它们的定义也可能不一致.您有责任退还明智的东西.编译器只需要一个或两个都不需要.

I've been reading about overloading true and false in C#, and I think I understand the basic difference between this and defining a bool operator. The example I see around is something like:

public static bool operator true(Foo foo) {
  return (foo.PropA > 0);
}
public static bool operator false(Foo foo) {
  return (foo.PropA <= 0);
}

To me, this is the same as saying:

public static implicit operator bool(Foo foo) {
  return (foo.PropA > 0);
}

The difference, as far as I can tell, is that by defining true and false separately, you can have an object that is both true and false, or neither true nor false:

public static bool operator true(Foo foo) { return true; }
public static bool operator false(Foo foo) { return true; }
//or
public static bool operator true(Foo foo) { return false; }
public static bool operator false(Foo foo) { return false; }

I'm sure there's a reason this is allowed, but I just can't think of what it is. To me, if you want an object to be able to be converted to true or false, a single bool operator makes the most sense.

Can anyone give me a scenario where it makes sense to do it the other way?

Thanks

解决方案

As the docs say, overloading true and false is intended to support (nullable) database-types (Yes/No, Y/N, 0/1, etc).

And of course you can define them inconsistently, as with any operator. It is your responsibility to return something sensible. The compiler goes no further than requiring neither or both.

这篇关于为什么要重载true和false而不是定义bool运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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