开发者

Comparing objects of value type N

开发者 https://www.devze.com 2022-12-26 16:31 出处:网络
What is the best way to compare objects of value type N?So I want to do a Str开发者_C百科ing, Integer, DateTime, etc comparison depending on the type of the object.IEqualityComparer<T>

What is the best way to compare objects of value type N? So I want to do a Str开发者_C百科ing, Integer, DateTime, etc comparison depending on the type of the object.


IEqualityComparer<T>

Where T is the type you want to compare.

IEqualityComparer(T) Interface (System.Collections.Generic)

...you could also fall back on Object.Equals() and ValueType.Equals()


Every simple types implements IComparable interface


static void Main(string[] args)
{

    Console.WriteLine(Compare<int>(1, 3));
    Console.WriteLine(Compare<string>("wil", "test"));
    Console.WriteLine(Compare<DateTime>(DateTime.Now, 
        DateTime.Now.AddDays(-1)));
    Console.ReadKey();
}

static int Compare<T>(T a, T b) where T : System.IComparable
{
    System.IComparable comparer = a;
    return comparer.CompareTo(b);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消