gpt4 book ai didi

c# - 如何使用 IEquatable 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 19:54:03 27 4
gpt4 key购买 nike

我正在研究接口(interface)的类型,但我不明白如何使用 IEquatable 接口(interface)

我认为它比直接使用a.Equals(b)提供了更好的性能,因为我们避免了拳击...我已经这样做了:

public interface IEquatable<T> { bool Equals(T other); }
class Test<T> where T:IEquatable<T>
{
public static bool IsEqual(T a, T b) { return a.Equals(b); }

}

但是当我要调用时,我在编译中遇到错误,我不太确定我是否正确调用了该方法:

int x = 2;
int y = 2;
Console.WriteLine(Test.IsEqual(x, y));

错误是:

Error CS0305 Using the generic type 'Test' requires 1 type arguments

编辑:我不太确定这段代码,但它有效:

class Test<T> where T:IEquatable<T>
{
public static bool Equals(T a, T b)
{
return a.Equals(b);

}
}


class Program
{
static void Main(string[] args)
{
int x = 2;
int y = 2;

bool check = Test<int>.Equals(x, y);
Console.WriteLine(check);
Console.ReadKey();
}
}

何时必须使用此代码?,我在《C#6 Nutshell O'reilly》一书中读到了此内容

最佳答案

Test 不是东西 - 只有 Test<T> 。您可以做的第一件事就是使类型成为非通用的,并且方法通用:

class Test 
{
public static bool IsEqual<T>(T a, T b)
where T : IEquatable<T>
{ return a.Equals(b); }
}

请注意,这仍然不好 - 它不能像 a 那样正确地工作 null ,但是......这并不重要,因为它仍然不会帮助你,因为 int 不实际上并没有实现你的 IEquatable<T> 。仅仅看起来正确的形状是不够的——它必须正式实现接口(interface)。幸运的是, int 确实System.IEquatable<T> 实现了内置 T==int ,因此只需完全删除接口(interface)定义即可。

但是,您在这里所做的一切都由 EqualityComparer<T>.Default 完成得更好。我建议:

class Test 
{
public static bool IsEqual<T>(T a, T b)
=> EqualityComparer<T>.Default.Equals(a,b);
}

(请注意,您不需要通用约束 - 它仍然可以正常工作,使用 IEquatable<T> 可用时,否则使用 object.Equals - 还考虑 nullNullable<T> 等)。


注意:如果您确实在这里只使用int,则应该只使用==:

Console.WriteLine(x == y);

当您只知道 T 时,应该使用通用的相等方法,其中调用者提供 T

关于c# - 如何使用 IEquatable 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328595/

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