gpt4 book ai didi

c# - 正确实现两个不同类型但语义等价的对象的比较

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

我发现了一个类似的问题

How to compare two distinctly different objects with similar properties

这可能会隐含地和/或部分地回答我的问题。

假设我想比较(没有很多嵌套条件)这个对象:

class ObjectA {
public string PropertyX { get; set; }
public char PropertyY { get; set; }
public long PropertyZ { get; set; }
}

System.String .我只对平等不平等感兴趣(不是关于身份的一系列值(value)观)。

实现 IEquatable<string>ObjectA是正确的选择吗?我不关心什么简单地工作,我想为这种情况确定正确的模式。

作为其他信息,请考虑 ObjectA通常会按 IEnumerable<ObjectA> 的顺序提供.

我不需要知道是否 "string" ==!= objectA实例;不涉及排序。

编辑以澄清(和帮助)

抱歉,有时很难写出一个好的问题...

假设我不能代表ObjectA作为用于比较目的的字符串(违反封装不是一种选择)。

  • 在 context-1 中,我必须将它与 PropertyY 进行匹配.

  • 在上下文 2 中,我必须将其与应用于 PropertyY 的算法进行匹配/PropertyZ .

问题末尾的@Oliver 解决方案再次帮助了我(并再次+1)。我可以简单地定义一个自定义接口(interface):

interface IContextConverter {
string ToEquatableStringForContext1();
string ToEquatableStringForContext2();
}

因为我还有一个 ObjectB具有相同的逻辑但不同的属性,两者都将实现 IContextConverter (或者也许我找到一个更好的名字)避免违反 RAP .

最佳答案

我强烈建议实现IEquatable<string> ,尤其是在处理集合、字典、LINQ 等时。您真的不知道何时会在内部某个深处调用这些方法之一,这可能会导致细微的错误。

由于您喜欢比较两个不同类型的对象,所以很简单 Comparer<T>也行不通。

所以要么写一个 TypeConverter 它将您的对象转换为所需的类型(在您的情况下为 string )或向您的对象添加一个方法,如 .ToEquatableString()并使用它们的输出将您的对象与其他字符串进行比较。

这是一个关于你可以获得所有元素的例子,这些元素与另一个集合中的一个字符串相匹配:

IEnumerable<String> otherElements = new[] {"abc", "def", "ghi" };
IEnumerable<ObjectA> myObjects = GetObjects();

var matchesFound = otherElements.Join( // Take the first collection.
myObjects, // Take the second collection.
s => s, // Use the elements in the first collection as key (the string).
obj => obj.ToEquatableString(), // Create a string from each object for comparison.
(s, obj) => obj, // From the matching pairs take simply the objects found.
StringComparer.OrdinalIgnoreCase); // Use a special string comparer if desired.

关于c# - 正确实现两个不同类型但语义等价的对象的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15275872/

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