C# How to use interfaces

前端 未结 4 765
不知归路
不知归路 2021-02-12 20:15

This is a relatively straight forward question. But I was wondering what the correct usage is for accessing a method inside a separate project through the use of an interface.

4条回答
  •  温柔的废话
    2021-02-12 21:01

    What ?

    Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.

    In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes

    Now Why ?

    Improves code re-usability

    Lets say you want to draw Circle, Triangle. You can group them together and call them Shapesand have methods to draw Circle and Triangle But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.

    With Interface you isolate the different implementation from the Contract


    How to use them ?

    Usage Scenario Day 1

    You were asked to create an App to Draw Circle and Triangle

    interface IShapes
    {
       void DrawShape();
    }
    
    class Circle : IShapes
    {
        
        public void DrawShape()
        {
            Console.WriteLine("Implementation to Draw a Circle");
        }
    }
    
    class Triangle : IShapes
    {
        public void DrawShape()
        {
            Console.WriteLine("Implementation to draw a Triangle");
        }
    }
    
    static void Main()
    {
         List  shapes = new List();
         shapes.Add(new Circle());
         shapes.Add(new Triangle());
    
         foreach(var shape in shapes)
         {
             shape.DrawShape();
         }
    }
    

    Usage Scenario Day 2

    If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());

提交回复
热议问题