Home  >  Article  >  Backend Development  >  Overloaded methods and ambiguity in C#

Overloaded methods and ambiguity in C#

WBOY
WBOYforward
2023-09-06 08:45:10759browse

C# 中的重载方法和歧义

Method overloading allows you to have multiple definitions of the same function name in the same scope. Function definitions must differ in the type and/or number of parameters in the parameter list.

Let's look at an example. Here, the call goes to a method with a single parameter -

Example

using System;

class Student {
   static void DisplayMarks(int marks1 = 90) {
      Console.WriteLine("Method with one parameter!");
   }

   static void DisplayMarks(int marks1, int marks2 = 95) {
      Console.WriteLine("Method with two parameters!");
   }

   static void Main() {
      DisplayMarks(97);
   }
}

Now let's see what causes an ambiguous call. The confusion here is that the second method requires two default parameters, while the first method requires one parameter to be defaulted. This creates ambiguity.

Example

using System;

class Student {
   static void DisplayMarks(int marks1 = 90, int marks2 = 80) {
      Console.WriteLine("Method with two parameters!");
   }

   static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) {
      Console.WriteLine("Method with three parameters!");
   }

   static void Main() {
      DisplayMarks(80);
   }
}

The above is the detailed content of Overloaded methods and ambiguity in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete