gpt4 book ai didi

c# - 我如何改进此代码 : Inheritance and IEquatable<>

转载 作者:可可西里 更新时间:2023-11-01 09:13:12 24 4
gpt4 key购买 nike

这是一个关于我正在尝试做的事情的例子:

public class Foo : IEquatable<Foo>
{
public bool Equals(Foo other)
{
Type type1 = this.GetType();
Type type2 = other.GetType();

if (type1 != type2)
return false;

if (type1 == typeof(A))
{
A a = (A)this;
A b = (A)other;

return a.Equals(b);
}
else if (type1 == typeof(B))
{
B c = (B)this;
B d = (B)other;

return c.Equals(d);
}
else
{
throw new Exception("Something is wrong");
}
}
}

public class A : Foo, IEquatable<A>
{
public int Number1 { get; set; }
public int Number2 { get; set; }

public bool Equals(A other)
{
return this.Number1 == other.Number1 && this.Number2 == other.Number2;
}
}

public class B : Foo, IEquatable<B>
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public int Number3 { get; set; }

public bool Equals(B other)
{
return this.Number1 == other.Number1 && this.Number2 == other.Number2 && this.Number3 == other.Number3;
}
}

但是正如您在上面看到的,我必须使用许多条件句“if”来识别真实类型。问题是我必须使用基类。例如:

A a = new A();
Foo foo = a;

foo.Equals(another);

最佳答案

作为对您问题的直接回答,您似乎实现了 IEquatable<Foo>通过始终遵循(具体的)子类的 IEquatable<self>执行。这看起来像:

(错误代码,仅供演示)

// You need to specify what you want when this method is called on a 
// vanilla Foo object. I assume here that Foo is abstract. If not, please
// specify desired behaviour.
public bool Equals(Foo other)
{
if (other == null || other.GetType() != GetType())
return false;

// You can cache this MethodInfo..
var equalsMethod = typeof(IEquatable<>).MakeGenericType(GetType())
.GetMethod("Equals");

return (bool)equalsMethod.Invoke(this, new object[] { other });
}

真的并不清楚为什么你需要相等比较总是“通过”基类的 IEquatable<self>实现。

框架已经有了虚拟Equals将导致将相等调用分派(dispatch)到适当方法的方法。此外,EqualityComparar<T>.Default (大多数集合类型使用它来进行相等性检查)已经有选择的智慧 IEquatable<self>.Equals(self)object.Equals(object)视情况而定。

据我所知,尝试在仅转发请求的基类中创建相等性的实现是没有任何值(value)

没有进一步解释为什么您需要基类 IEquatable<>实现,我建议只对每种类型正确实现平等。例如:

public class A : Foo, IEquatable<A>
{
public int Number1 { get; set; }
public int Number2 { get; set; }

public bool Equals(A other)
{
return other != null
&& Number1 == other.Number1
&& Number2 == other.Number2;
}

public override bool Equals(object obj)
{
return Equals(obj as A);
}

public override int GetHashCode()
{
return Number1 ^ Number2;
}
}

关于c# - 我如何改进此代码 : Inheritance and IEquatable<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051187/

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