小编Jep*_*eSN的帖子

对IComparable对象进行排序,其中一些对象为null

大多数人在编写实现IComparable <T>的refence类型(类)时,使用null比任何实际对象都少的约定.但是如果你尝试使用相反的约定,会发生一些有趣的事情:

using System;
using System.Collections.Generic;

namespace SortingNulls
{
  internal class Child : IComparable<Child>
  {
    public int Age;
    public string Name;

    public int CompareTo(Child other)
    {
      if (other == null)
        return -1; // what's your problem?

      return this.Age.CompareTo(other.Age);
    }

    public override string ToString()
    {
      return string.Format("{0} ({1} years)", this.Name, this.Age);
    }
  }

  internal static class Program
  {
    private static void Main()
    {
      var listOfChilds = new List<Child>
      {
        null,
        null,
        null,
        null,
        new Child { Age = 5, Name = …
Run Code Online (Sandbox Code Playgroud)

.net c# null icomparable

6
推荐指数
1
解决办法
3708
查看次数

标签 统计

.net ×1

c# ×1

icomparable ×1

null ×1