gpt4 book ai didi

c# - 等同于 2 个对象 - 每次都不同?

转载 作者:太空宇宙 更新时间:2023-11-03 22:02:40 25 4
gpt4 key购买 nike

我有一个类:

  public class Person
{
public string name { get; set; }
public int age { get; set; }
}

Person p1 = new Person() { age=1, name="a" };
Person p2 = new Person() { age = 1, name = "b" };

我想做类似的事情

p1.equals(p2)

但按年龄按名字

我的意思不是添加到字典的方式(并使用 Iequatable...)

Equals 方法内部没有任何 Helper ...

enter image description here

有什么办法可以让他发送我的特定助手类,就像:

   Dictionary<PersonForDictionary, int> dct2 =
new Dictionary<PersonForDictionary, int>(new helperClass()); // here helperclass is a class which I gave him - and told the dictionary how to equate objects....

我正在寻找一个类似 的解决方案来等同对象。 (不是字典模式)。

最佳答案

可能是,也可能是对 IComparable 进行不同的实现。例如:

public class Person
{
public string name { get; set; }
public int age { get; set; }

pulbic int ComparePerson(Person person, IComparable comparer)
{
return comparer.Compare(this, person);
}
}

实现不同类后:

public class PersonNameComparer : IComparer
{
}

或另一个

public class PersonAgeComparer : IComparer
{
}

并在内部使用它:

Person p1 = new Person() { age=1, name="a" };
Person p2 = new Person() { age = 1, name = "b" };

p1.Compare(p2, new PersonNameComparer ());
p1.Compare(p2, new PersonAgeComparer ());

关于c# - 等同于 2 个对象 - 每次都不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548503/

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