Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

.net - C# compare two objects of unknown types (including reference and value types)

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
}

Which would return

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...