我在 C# 中有一个类函数,用于将一个对象与另一个对象进行比较。或多或少是一个 Equals 函数,但添加了一些代码。我的对象有很多变量,我想比较每个变量,如果有不同,将它们添加到数据表中。现在我的函数看起来像:
public bool compareSysInfo(SystemInfo expected, SystemInfo comp)
{
ComparePopup popup = new ComparePopup();
bool finalResult = true;//initial assumption that they are equal
//compares branding
if (expected.branding != comp.branding)
{
finalResult = false;
popup.addDataToTable("Branding", comp.getBranding() + "", expected.getBranding() + "");
}
//compares pro #
if (expected.getPro() != comp.getPro())
{
finalResult = false;
popup.addDataToTable("Pro Number", comp.getPro() + "", expected.getPro() + "");
}
它对所有变量都如此。我想避免过多的 if 语句,有没有办法创建抽象方法并使用循环?我调查了代表,但我不确定如何在这种情况下使用它们。也许我做错了,应该做一些完全不同的事情,比如将它们添加到集合中,然后只使用 for 循环来比较对象。我觉得我错过了一些明显的东西。我知道任何有重复代码的地方都可以更好地实现,只是我不知道如何实现。这里的任何建议都会很棒。 感谢您的帮助。
最佳答案
创建一个策略类,为每个规则继承它,并为您的类提供一个包含以下内容的列表:
public MyClass {
readonly IEnumerable<Rule> _rules;
public MyClass(IEnumerable<Rule> rules) {
_rules
}
public bool CompareSysInfo(SystemInfo expected, SystemInfo comp) {
// i prefer linq over loops
var result = from r in _rules
where !r.CheckRule(expected, comp)
select false;
return result.Count() > 0; // only returns true if no rule checks return false
}
}
然后对于每个规则检查,您实现一个 Rule 类(或接口(interface))的实例:
public abstract class Rule {
protected ComparePopup Popup { get; private set; }
protected Rule(ComparePopup popup) {
Popup = popup;
}
public abstract bool CheckRule(SystemInfo expected, SystemInfo comp);
}
public class BrandingRule : Rule {
public BrandingRule(ComparePopup popup) : base(popup) { }
public override bool CheckRule(SystemInfo expected, SystemInfo comp) {
var result = expected.branding == comp.branding;
if(!result)
Popup.addDataToTable("Branding", comp.getBranding() + "", expected.getBranding() + "");
}
}
此策略使您能够添加、删除或修改规则以及它们独立于需要使用它们的代码执行的操作。
关于c# - 在 C# 中创建一个具有许多要比较的变量的 equals 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10340034/