【问题标题】:How to perform loose equality operator in c#? [closed]如何在 C# 中执行松散相等运算符? [关闭]
【发布时间】:2023-03-17 07:42:02
【问题描述】:

在 C# 中是否有 JavaScript 松散相等运算符的 == 等效项?还是函数?

例子

// JavaScript ‘==' operator 
console.log(21 == 21); //true
console.log(21 == "21");  // true
console.log("food is love"=="food is love"); //true
console.log(true == 1);  //true
console.log(false == 0);  //true

【问题讨论】:

  • 其实很有趣的问题。我不确定是否存在,但是据我所知,您可以覆盖“==”操作,这样您就可以实现与类类似的效果。
  • 不,因为这个概念不适用。例如,您无法比较 intstring 而不进行显式转换。所以 - 除非您使用 dynamic 放弃强静态类型的所有好处,否则您必须在编译时知道您正在比较的类型。
  • 谢谢,我现在更清楚了。
  • @Vulpex 不能为您不创建的类型重载/重新定义运算符(所有给定的示例都使用内置类型,固定定义为 ==
  • @CaiusJard 因此添加了with classes 但我同意再读一遍,我可以更清楚地说明它只适用于非内置类型。感谢您指出。

标签: javascript c# operators


【解决方案1】:

不,但您可以编写一个并为您的案例提供一堆重载。例如这些进行 bool/int 比较:

static class Ext {
    public static bool Eq(this bool a, int b) => b.Eq(a);

    //e.g. a!=0 converts 0 to false, other to true, then compare of bool:bool is possible
    public static bool Eq(this int a, bool b) => b == (a != 0); 
}

Console.WriteLine(false.Eq(1));

如果你将它们作为扩展方法,那么它们就会变成a.Eq(b) 而不是Eq(a, b),所以它们读起来更像a == b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2014-03-27
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多