gpt4 book ai didi

c# - 如何覆盖 C# 中接口(interface)的等号运算符 ==?

转载 作者:可可西里 更新时间:2023-11-01 03:06:09 25 4
gpt4 key购买 nike

我定义了以下接口(interface):

public interface IHaveAProblem
{
string Issue { get; set; }
}

下面是IHaveAProblem的实现:

public class SomeProblem : IHaveAProblem
{
public string Issue { get; set; }

public override bool Equals(object obj)
{
SomeProblem otherObj = obj as SomeProblem;

if (otherObj == null)
{
return false;
}

return this.Issue == otherObj.Issue;
}

public override int GetHashCode()
{
return base.GetHashCode();
}

public static bool operator ==(SomeProblem rhs, SomeProblem lhs)
{
// Null check
if (Object.ReferenceEquals(rhs, null) || Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null) && Object.ReferenceEquals(lhs, null))
{
// Both are null. They do equal each other
return true;
}

// Only 1 is null the other is not so they do not equal
return false;
}

return rhs.Equals(lhs);
}

public static bool operator !=(SomeProblem rhs, SomeProblem lhs)
{
// Null check
if (Object.ReferenceEquals(rhs, null) || Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null) && Object.ReferenceEquals(lhs, null))
{
// Both are null. They do equal each other
return false;
}

// Only 1 is null the other is not so they do not equal
return true;
}

return !rhs.Equals(lhs);
}
}

当我使用该对象时,我可以获得==比较的正确结果:

SomeProblem firstTest = new SomeProblem()
{
Issue = "Hello World"
};

SomeProblem secondTest = new SomeProblem()
{
Issue = "Hello World"
};

// This is true
bool result = firstTest == secondTest;

但是,当我尝试比较接口(interface)时,它是在进行内存比较,而不是 SomeProblem 上的运算符 ==:

IHaveAProblem firstProblem = new SomeProblem()
{
Issue = "Hello World"
};

IHaveAProblem secondProblem = new SomeProblem()
{
Issue = "Hello World"
};

是否可以让接口(interface)在 SomeProblem 上使用 == 而不是内存比较?

我知道我可以执行 firstProblem.Equals(secondProblem) 并获得正确的结果。但是,我正在创建一个框架,我不会知道它最终是如何使用的。我认为 == 会正常工作。

最佳答案

运算符== 是静态的。不能在 C# 中为接口(interface)定义静态方法。此外,对于所有运算符,至少有一个参数类型需要与定义它的类具有相同的类型,因此:接口(interface)没有运算符重载:(

您可以做的是改用抽象类 - 并在那里定义运算符。同样,运算符不能是虚拟的(因为静态方法不能是虚拟的...)

[已编辑,原因见评论。]

关于c# - 如何覆盖 C# 中接口(interface)的等号运算符 ==?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1881459/

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