C#:编译器是否可以自动调用方法?

C#: Is it possible for the compiler to auto-call a method?

在此代码中,未显式调用 CompareTo() 方法,而 max() 给出了正确的结果。所以,我的问题是:CompareTo() 是否有可能被称为 implicitly/auto-call?如果是这样,我怎么知道其他 function/method 可以隐式调用?请帮我理解,谢谢! 结果:史蒂夫

public class Student : IComparable<Student> 
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
    public int StandardID { get; set; }

    public int CompareTo(Student other)
    {
        if (this.StudentName.Length >= other.StudentName.Length)
        return 1;

        return 0;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Student collection
        IList<Student> studentList = new List<Student>>() { 
                new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
                new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
                new Student() { StudentID = 5, StudentName = "Steve" , Age = 15 } 
            };
        var studentWithLongName = studentList.Max();

        Console.WriteLine("Student Name: {1}", studentWithLongName.StudentName);

    }
}

正如 Jeroen 所说,您正在调用 IEnumerable.Max() 方法。

基本上那个函数在做什么 "in the shadows" 与此类似:

private static T Max<T>(IEnumerable<T> source) where T : IComparable<T>
{
  if (source == null)
    throw new ArgumentNullException(nameof(source));

  bool isMaxSet = false;
  T max;
  foreach (T item in source)
  {
    if (isMaxSet == false)
    {
      max = item;
      isMaxSet = true;
    }
    else
    {
      if (max.CompareTo(item) < 0) // here's where it's used!
        max = item;
    }
  }

  if (isMaxSet == false)
    throw new InvalidOperationException();

  return max;
}

此外,请注意您的 int CompareTo(Student) 功能不完整,使用它可能会导致意外结果。

https://docs.microsoft.com/en-us/dotnet/api/system.icomparable.compareto?view=netframework-4.8 中所述,其工作方式如下:

Less than zero: This instance precedes obj in the sort order.

Zero: This instance occurs in the same position in the sort order as obj.

Greater than zero: This instance follows obj in the sort order.