SoFunction
Updated on 2025-03-07

Share examples of using c# interface

1. Interface:

Like abstract classes, interfaces also represent certain rules. Once this rule is used, relevant methods must be implemented. For C# language, since it can only inherit from one parent class, if multiple rules need to be implemented, it is a better practice to use interfaces.

2. Definition of interface

Copy the codeThe code is as follows:

interface interface name
{
Method declaration;
}

3. If there are multiple methods with the same name in different interfaces, you need to explicitly specify the interface name, for example:

4. Use of interfaces

Polymorphism can also be achieved using interfaces.

The code is as follows:

Copy the codeThe code is as follows:

class Program
{
    static void Main(string[] args)
    {
//Provide three categories to complete the calculation of salary
        List<ICalu> list = new List<ICalu>();
        (new Boss());
        (new Clert());
        (new Clert());
        (new Customer());
        foreach (ICalu emp in list)
        {
(); //Polymorphic
        }
    }
}

class Boss : ICalu
{
    public  void Calu()
    {
("Calculate the boss's salary");
    }
}
class Customer : ICalu
{
    public  void Calu()
    {
("Calculate customer salary");
    }
}
class Clert : ICalu
{
    public  void Calu()
    {
("Calculate employee salary");
    }
}
interface ICalu
{
    void Calu();
}



5. Examples of interface application occasions

6. Interface demo
 

Copy the codeThe code is as follows:

using System;
using ;
using ; using ;
namespace ConsoleApplication1 {

    class Program     {    
    static void Main(string[] args)         {   
         List<IShow> list = new List<IShow>();     
       (new Map());    
        (new Voice());  
          (new Video());   
         (new ThreeD());
            foreach(IShow ishow in list)             {     
           ();             }  
      } 
   } 
    interface IShow     {   
     void Show();     }  
  public class Map:IShow     {   
     public void Show()     
   {      
("Show pictures");        }

   public class Voice : IShow     {   
     public void Show()         {  
("Play sound");         }
    }  
  public class Video : IShow     {  
      public void Show()  
      {        
("Show video");         }
   }     public class ThreeD : IShow     { 
       public void Show()         {   
("3D interaction");        }
}
}