C#中比较未知类型的两个对象(包括参考和值类型) [英] C# compare two objects of unknown types (including reference and value types)

查看:246
本文介绍了C#中比较未知类型的两个对象(包括参考和值类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在C#中如果存在使用其类型比较来比较未知类型(包括参考和值类型)的两个对象?

Is it possible in C# to compare two objects of unknown types, (including both reference and value types) using their type comparators if they exist?

我们的目标是编写,将有一个功能,这样的签名:

The goal is to write a function that would have a signature like this:

public bool Compare(object a, object b)
{
     // compare logic goes here
}

这将返回

Compare(100d, 100d) == true
Compare(100f, 100f) == true
Compare("hello", "hello") == true
Compare(null, null) == true 
Compare(100d, 101d) == false
Compare(100f, null) == false

// Use type comparators where possible, i.e.:
Compare(new DateTime(2010, 12, 01), new DateTime(2010, 12, 01)) == true
Compare(new DateTime(2010, 12, 01), new DateTime(2010, 12, 02)) == false
Compare(new DateTime(2010, 12, 01), null) == false

有没有一种通用的方法来解决这个问题,将适用于任何类型的对象?

Is there a generic approach to solving this problem that would work for any type of object?

推荐答案

您可以使用静态的Object.Equals(对象x,对象Y)方法,而不是打扰写作你的方法在所有。这将妥善处理空值,并委托给的Object.Equals(对象)与任何 X 或相关<的实现code>是 ...它的不应该的事项,如等于,就是要对称

You can use the static object.Equals(object x, object y) method and not bother writing your method at all. That will handle nulls appropriately, and delegate to an implementation of object.Equals(object) associated with either x or y... it shouldn't matter which, as Equals is meant to be symmetric.

请注意,这的的使用==操作符任何类型 - 运营商不能被覆盖,只有超载(这意味着它们在正在选择的编译时间,不是的执行时间的。在大多数情况下等于应该做你想做的。在某些情况下,==不得即使超载等于被覆盖......但是我从来不知道反在我使用过的任何类型是真实的。

Note that this doesn't use the == operators for any type - operators can't be overridden, only overloaded (which means they're chosen at compile-time, not execution-time. In most cases Equals should do what you want. In some cases, == may not be overloaded even though Equals is overridden... but I've never known the reverse to be true in any types I've worked with.

请注意,使用此方法将的的任何值类型...

Note that using this approach will box any value types...

编辑: - 很差 - 删除了有关重新实现有效截面 EqualityComparer&LT; T&GT; .DEFAULT 。见马克的答案更多。这不会帮助你,如果你不能使用过程中的泛型类型。

Removed section about effectively reimplementing - poorly - EqualityComparer<T>.Default. See Marc's answer for more. This won't help you if you can't use a generic type, of course.

最后一点:我的的调用你的方法比较。该名称通常是与相关的的值,而不是比较它们是否相等。

One final point: I wouldn't call your method Compare. That name is usually associated with ordering values rather than comparing them for equality.

这篇关于C#中比较未知类型的两个对象(包括参考和值类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆