gpt4 book ai didi

c# - 通用函数中的 equals() 和 ==

转载 作者:太空狗 更新时间:2023-10-29 23:24:50 25 4
gpt4 key购买 nike

我正在为各种类型的集合操作制作一个比较器。

所以我有一个泛型类

 public class Comparer<T, Tid>
...
public bool Equals(T x, T y)
{
var xid = m_idfunc(x);
var yid = m_idfunc(y);
return (Tid)xid == (Tid)yid;
}

其中m_idfunc是传入Comparer构造函数的lambda,是

Func<T,Tid>

我用 Tid = string 创建了一个比较器。我在 equals 函数中得到 xid = string1, yid = string2

如果字符串 1 和字符串 2 相同("foo"和 "foo"说)

xid == yid

产生错误

(Tid)xid == (Tid)yid

也会产生 false(没有必要——我只是变得绝望了)

这是我的即时窗口 - 在返回 xid == yid 行暂停

yid.GetType() == typeof(string)
true
xid.GetType() == typeof(string)
true
xid==yid
false
(string)xid==(string)yid
true
xid.Equals(yid)
true

这是怎么回事?

最佳答案

有趣的是,它可能会按照您希望的方式工作。这是一个例子:

using System;
using System.Text;

namespace ConsoleApplication1 {

class Program {

public static void Main() {
string myString = "1";
object objectString = "1";
string myCopiedString = string.Copy(myString);
string internedString = string.Intern(myCopiedString);

Console.WriteLine(myString); //1
Console.WriteLine(objectString); //1
Console.WriteLine(myCopiedString); //1
Console.WriteLine(internedString); //1

Console.Write(objectString == myString); //true
Console.Write(objectString == "1"); //true
Console.Write(objectString == myCopiedString); //!!!FALSE!!!!
Console.Write(objectString == internedString); //true
Console.Write(objectString == SomeMethod()); //!!!FALSE!!!
Console.Write(objectString == SomeOtherMethod()); //true
}

public static string SomeMethod() {
StringBuilder sb = new StringBuilder();
return sb.Append("1").ToString();
}

public static string SomeOtherMethod() {
return "1".ToString();
}
}
}

可能 起作用的原因是字符串驻留。所以,这绝对是一个需要注意的问题,因为当你测试它时它实际上可以工作,但根据实现情况,它可能会突然崩溃。

在您的情况下,您需要确定您是关心引用相等性还是“值”相等性。 == 是引用相等性,这同样取决于字符串是否被 interned 可能为真。我怀疑你真的想使用 EqualityComparer<T>.Default.Equals在你的函数中。

如果您在 VS 中运行 open this,您将看到编译器警告:“Possible unintended reference comparison;要进行值比较,请在左侧输入“string”。但是,在您的情况下,编译器无法警告您,因为据它所知,类型是对象,它不知道其中一个或两者都是字符串。

关于c# - 通用函数中的 equals() 和 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12394195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com