English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Polymorphism

Polymorphism is the ability of the same behavior to have multiple different expressions or forms.

PolymorphismIt means there are multiple forms. In the object-oriented programming paradigm, polymorphism is often expressed as "one interface, multiple functions".

Polymorphism can be static or dynamic. InStatic polymorphismIn, the response of the function occurs at compile time. Indynamic polymorphismIn, the response of the function occurs at runtime.

In C#, each type is polymorphic because all types, including user-defined types, inherit from Object.

Polymorphism is the same interface, using different examples to perform different operations, as shown in the figure:

In reality, for example, when we press F1 This action: key

  • If it is in the Flash interface, it will be AS 3 Help documentation;

  • If it is in Word, it will be Word Help;

  • On Windows, it is the Windows Help and Support that pops up.

The same event occurring on different objects can produce different results.

Static polymorphism

At compile time, the mechanism of binding functions and objects is called early binding, also known as static binding. C# provides two techniques to implement static polymorphism. They are:

  • Function overloading

  • Operator overloading

Operator overloading will be discussed in the next chapter, and then we will discuss function overloading.

Function overloading

You can have multiple definitions of the same function name in the same scope. The definitions must be different from each other, which can be different parameter types in the parameter list, or different numbers of parameters. You cannot overload a function declaration that only differs in return type.

The following example demonstrates several identical functions Add()to handle addition of different numbers of parameters:

using System;
namespace PolymorphismApplication
{}}
    public class TestData  
    {}}  
        public int Add(int a, int b, int c)  
        {}}  
            return a + b + c;  
        }  
        public int Add(int a, int b)  
        {}}  
            return a + b;  
        }  
    }  
    class Program  
    {}}  
        static void Main(string[] args)  
        {}}  
            TestData dataClass = new TestData();
            int add1 = dataClass.Add(1, 2);  
            int add2 = dataClass.Add(1, 2, 3);
            Console.WriteLine("add1 :" + add1);
            Console.WriteLine("add2 :" + add2);  
        }  
    }  
}

The following example demonstrates several identical functions print()to print different data types:

using System;
namespace PolymorphismApplication
{}}
   class Printdata
   {}}
      void print(int i)
      {}}
         Console.WriteLine("Output integer type: {0}", i);
      }
      void print(double f)
      {}}
         Console.WriteLine("Output floating-point type: {0}", f);
      }
      void print(string s)
      {}}
         Console.WriteLine("Output string: {0}", s);
      }
      static void Main(string[] args)
      {}}
         Printdata p = new Printdata();
         // Call print to print an integer
         p.print(1);
         // Call print to print a floating-point number
         p.print(1.23);
         // Call print to print a string
         p.print("Hello w3codebox");
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it will produce the following results:

Output integer type: 1
Output floating-point type: 1.23
Output string: Hello w3codebox

dynamic polymorphism

C# allows you to use the keyword abstract Create an abstract class to provide the implementation of part of the interface. When a derived class inherits from this abstract class, the implementation is completed.Abstract classContains abstract methods, abstract methods can be implemented by derived classes. Derived classes have more specialized functions.

Please note that the following are some rules about abstract classes:

  • You cannot create an instance of an abstract class.

  • You cannot declare an abstract method outside an abstract class.

  • by placing the keyword sealed, the class can be declared assealed class. When a class is declared as sealed At this time, it cannot be inherited. An abstract class cannot be declared as sealed.

The following program demonstrates an abstract class:

using System;
namespace PolymorphismApplication
{}}
   abstract class Shape
   {}}
       abstract public int area();
   }
   class Rectangle : Shape
   {}}
      private int length;
      private int width;
      public Rectangle(int a=0, int b=0)
      {}}
         length = a;
         width = b;
      }
      public override int area()
      {}} 
         Console.WriteLine("Area of Rectangle class:");
         return (width * length); 
      }
   }
   class RectangleTester
   {}}
      static void Main(string[] args)
      {}}
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}", a);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it will produce the following results:

Area of Rectangle class:
Area: 70

When a function defined in a class needs to be implemented in a derived class, you can useVirtual method.

Virtual methods are declared using the keyword virtual declared.

Virtual methods can have different implementations in different derived classes.

the call to a virtual method occurs at runtime.

Dynamic polymorphism is achieved through Abstract class and Virtual method implemented.

The following example creates a Shape base class and creates derived classes Circle, Rectangle, Triangle. The Shape class provides a virtual method named Draw, which is overridden in each derived class to draw the specified shape of the class.

using System;
using System.Collections.Generic;
public class Shape
{}}
    public int X { get; private set; }
    public int Y { get; private set; }
    public int Height { get; set; }
    public int Width { get; set; }
   
    // Virtual method
    public virtual void Draw()
    {}}
        Console.WriteLine("Executing the drawing task of the base class");
    }
}
class Circle : Shape
{}}
    public override void Draw()
    {}}
        Console.WriteLine("Draw a circle");
        base.Draw();
    }
}
class Rectangle : Shape
{}}
    public override void Draw()
    {}}
        Console.WriteLine("Draw a rectangle");
        base.Draw();
    }
}
class Triangle : Shape
{}}
    public override void Draw()
    {}}
        Console.WriteLine("Draw a triangle");
        base.Draw();
    }
}
class Program
{}}
    static void Main(string[] args)
    {}}
        // Create a List<Shape> object and add Circle, Triangle, and Rectangle to the object
        var shapes = new List<Shape>
        {}}
            new Rectangle(),
            new Triangle(),
            new Circle()
        };
        // Use the foreach loop to iterate over the derived classes in the list and call the Draw method on each Shape object 
        foreach (var shape in shapes)
        {}}
            shape.Draw();
        }
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

When the above code is compiled and executed, it will produce the following results:

Draw a rectangle
Execute the drawing task of the base class
Draw a triangle
Execute the drawing task of the base class
Draw a circle
Execute the drawing task of the base class
Press any key to exit.

The following program demonstrates calculating the area of different shape images by using the virtual method area():

using System;
namespace PolymorphismApplication
{}}
   class Shape 
   {}}
      protected int width, height;
      public Shape(int a = 0, int b = 0)
      {}}
         width = a;
         height = b;
      }
      public virtual int area()
      {}}
         Console.WriteLine("Area of the parent class:");
         return 0;
      }
   }
   class Rectangle: Shape
   {}}
      public Rectangle(int a = 0, int b = 0): base(a, b)
      {}}
      }
      public override int area()
      {}}
         Console.WriteLine("Area of Rectangle class:");
         return (width * height); 
      }
   }
   class Triangle: Shape
   {}}
      public Triangle(int a = 0, int b = 0): base(a, b)
      {}}
      
      }
      public override int area()
      {}}
         Console.WriteLine("Area of Triangle class:");
         return (width * height / 2); 
      }
   }
   class Caller
   {}}
      public void CallArea(Shape sh)
      {}}
         int a;
         a = sh.area();
         Console.WriteLine("Area: {0}", a);
      }
   }  
   class Tester
   {}}
      
      static void Main(string[] args)
      {}}
         Caller c = new Caller();
         Rectangle r = new Rectangle(10, 7);
         Triangle t = new Triangle(10, 5);
         c.CallArea(r);
         c.CallArea(t);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it will produce the following results:

Area of Rectangle class:
Area:70
Area of Triangle class:
Area:25