如何在 C# 中执行松散相等运算符?

How to perform loose equality operator in c#?

在 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

不,但是你可以写一个并为你的案例设置一堆重载。比如这些 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