c# - 如何在 C# 中比较两个不同类对象的相同属性?

标签 c# nuget

我有两个类 A 和 B,它们具有一些相同的属性。我正在寻找一种方法来仅比较相同的属性,并希望是否有一些 nuget 包可以为任何类型的类执行此操作。

我不知道如何去寻找这样的 nuget 包,我已经尝试使用 if 语句来比较相同的属性,但我有很多这样的情况,所以使用 nuget 包会更容易去做。

另外,这里不可能包含继承,因为这两个类在逻辑上没有联系。

class A {
  string title;
  DateTime publishDate;
  string Author;
  int numberOfSales;
}
class B {
  DateTime publishDate;
  int numberOfSales;
}

我已经做过类似的事情来比较两个相同的属性

if (A.publishDate.Equals(B.publishDate)) {
  // Do something
}
if (A.numberOfSales == B.numberOfSales) {
  // Do something
}

如果有人能告诉我是否有一些 nuget 包可以比较两个类的相同属性,我将不胜感激。

最佳答案

为什么不在 C# 中使用 native 接口(interface)?

你可以像这样使用 Icomprable 接口(interface):

 public class A:IComparable<B>
        {
            public string title;
            public DateTime publishDate;
            public string Author;
            public int numberOfSales;
            public int CompareTo(B other)
            {
                if (this.numberOfSales == other.numberOfSales && this.publishDate.Equals(other.publishDate))
                    return 0;
                if (this.numberOfSales != other.numberOfSales && this.publishDate.Equals(other.publishDate))
                    return 1;
                if (this.numberOfSales == other.numberOfSales && !this.publishDate.Equals(other.publishDate))
                    return 2;
                return -1;
            }
        }
        public class B
        {
            public DateTime publishDate;
            public int numberOfSales;
        }

然后你可以像这样使用它:

  switch (aClass.CompareTo(bClass))
            {
                case 0:Console.WriteLine("both properties are equal");break;
                case 1:Console.WriteLine("PublishDate only equal"); break;
                case 2: Console.WriteLine("NumberOfSales only equal"); break;
                case -1: Console.WriteLine("None are equal"); break;
            }

希望有用

关于c# - 如何在 C# 中比较两个不同类对象的相同属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968227/

相关文章:

c# - 如何以编程方式获取特定服务器标识

c# - 使用 dapper 选择

c# - C#:有关引发适当类型的异常的文章

c# - 使用带参数的数据表 sAjaxSource

nuget - 获取 Nuget 包的发布日期

asp.net-core - 在 ASP.NET Core 2.0 中哪里可以找到 System.DirectoryServices?

c# - 带有 Azure Linux VM 的 Couchbase

visual-studio - Visual Studio 添加自定义命令以在包管理器控制台中运行?

nuget.config被忽略,特别是repositoryPath

azure - 无法将 Microsoft.Azure.Devices 添加到 ASP.NET 5 项目 : can't find fx/System.Net.Http.Formatting