是否在电源外壳测试引用相等或使用的Object.Equals当量关键字()当量、外壳、关键字、电源

2023-09-04 10:30:06 作者:摆摆舞、の中枪舞、

是否(在C#中,如==)在PowerShell中测试参考平等当量或是否做主叫的Object.Equals相当于()

Does "-eq" in Powershell test reference equality (like "==" in c#) or does it do the equivalent of calling Object.Equals()

推荐答案

在平等的测试不是那么简单了。

The test on equality is not so simple.

考虑到'A'当量'A'返回true。这意味着,PowerShell中做一些事情不仅仅是打电话等于。

Consider that 'a' -eq 'A' returns true. That means that PowerShell does something more than just call Equals.

另外为对象等于被称为预期。

Further for your objects Equals is called as expected.

Add-Type -TypeDefinition @"
    using System;
    public class X {
        public string Property;
        public X(string s) {
            Property = s;
        }
        public override bool Equals(object o) {
            System.Console.WriteLine("equals on {0}", Property);
            return Property == ((X)o).Property;
        }
        public override int GetHashCode() { return 20; }
    }
"@

$o1 = New-Object X 'a'
$o2 = New-Object X 'A'

$o1 -eq $o2

除此之外PowerShell使用转换相当严重。因此,如果操作数是相同的类型,则右操作数被转换为左操作数的类型。 这就是为什么'1'当量1 成功。

Besides that PowerShell uses conversion quite heavily. So if the operands are not of the same type, the right operand is converted to the type of the left operand. That's why '1' -eq 1 succeeds.