C# basic interface learning

C# basic interface learning

1. Definition

The interface provides a kind of norms and constraints for the realization of different applications. As long as each application complies with this kind of norms and constraints, the entire system can be effectively organized, thus providing an effective way for the low-cost development of the application system.

The interface is defined using the interface keyword and can be composed of methods, attributes, events, indexers, or any combination of these four member types. It does not implement any methods or attributes, but only tells the inheriting class which functions should be implemented at least , and the inheriting class can add its own methods.

Interface statement:

    interface ISample
    {
        void Sample(int x);                              //方法
        int count { get; set; }                       //属性(可读,可写)
        event EventHandler OnDraw;                  //事件
        string this[int index] { get; set; }        //索引器
    }

2. Features

  •  An interface is similar to an abstract class and cannot be instantiated directly

  • The methods in the interface are abstract methods ( not defined as abstract methods ), any non-abstract class that implements the interface must implement all the members of the interface

  • When the members of the interface are explicitly implemented, the members can only be accessed through the interface instance

When the members of the interface are implemented implicitly, the members can be accessed through the class instance, and the members can also be accessed through the interface instance

Either way, the premise is that the members must be public

  • Interfaces cannot guarantee constants, fields, operators, strength constructors, static members, destructors or types, etc.

  • Interface members are automatically public and cannot contain any access modifiers

  • An interface can inherit from multiple interfaces, a class or structure can inherit multiple interfaces, but interfaces cannot inherit classes

  • When a class inherits both the base class and the interface, the base class must be written in front, and the base class and the interface must be separated by a comma. A class can only have one base class, but can inherit multiple interfaces

Explanation on the explicit implementation of the interface and the implicit implementation of the interface:

(1) Implicitly implement the interface

Create an IChinese interface, including a Speak member

namespace InterfaceLearn
{
    public interface IChinese
    {
        string Speak();
    }
}

Create a Speaker class to inherit this interface and implement interface members

namespace InterfaceLearn
{
    public class Speaker:IChinese
    {
        public string Speak()
        {
            return "中文";
        }
    }
}

Implicitly implement the calling method:

(Access members through the interface instance)

or

(Access members through class instances)

(2) Display implementation interface

Create an IEnglish interface, including a Speak member

namespace InterfaceLearn
{
    public interface IEnglish
    {
        string Speak();
    }
}

Create an English class to inherit the interface and implement interface members


namespace InterfaceLearn
{
    public class English:IEnglish
    {
        string IEnglish.Speak()
        {
            return "英语";
        }
    }
}

Explicitly implement the calling method:

( Members can only be accessed through the interface instance)

If a class instance is used to access members, the following situations will occur:

 3. The difference between interface and abstract class

  1. Interface is used for specification, abstract class is used for commonality

  2. Abstract classes cannot be instantiated, but they can have their own member fields and non-abstract methods, but interfaces are more abstract than abstract classes, and their members can only be general methods, attributes and index functions, and cannot have their own member fields and constructors. ,

  3. Abstract classes are classes, so they can only be inherited by single, but interfaces can implement multiple inheritance at once

  4. Abstract classes can provide partial implementations of certain methods, but interfaces cannot

  5. Interfaces, abstract classes, and non-abstract classes can all inherit interfaces

  6. The methods in the abstract class declared with abstract must be modified by keywords such as access modifiers such as public. Secondly, the methods in the abstract class must be declared as abstract methods with abstract or virtual as virtual methods (except for non-abstract methods, virtual methods) There is a simple execution code, the derived class can choose not to rewrite, the abstract method has no execution code, and the derived class must be rewritten). When rewriting abstract methods or virtual methods in its derived class, it must be modified with override. The interface methods in the interface declared with interface are not allowed to be static first, and secondly, no access restriction modifiers can be added except for no execution code, and they cannot be modified with virtual or abstract. At the same time, the override modifier cannot be used to override methods in the inherited interface class, and all methods in the inherited interface must be implemented, but the new keyword can be used to hide the methods in the parent interface.

 

Full example:

1. Create two interfaces: IPerson, IStudent

namespace InterfaceLearn
{
    public interface IPerson
    {
        string Name { get; set; }
        void Show(string name);
    }
}
namespace InterfaceLearn
{
    public interface IStudent
    {
        string StudentId { get; set; }
        void Show(string studentId);
    }
}

 2. Create a Student class to inherit two interfaces (including explicit implementation and implicit implementation)

namespace InterfaceLearn
{
    public class Student : IPerson, IStudent
    {
        //隐式实现接口
        private string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }

        public void Show(string name)
        {
            Console.WriteLine("姓名为{0}", name);
        }

        //显式实现接口
        private string _studentId;
        string IStudent.StudentId
        {
            get
            {
                return _studentId;
            }
            set
            {
                _studentId = value;
            }
        }

        void IStudent.Show(string studentId)
        {
            Console.WriteLine("学号为{0}", studentId);
        }
    }
}

3. Execute the code

namespace InterfaceLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            Console.WriteLine("输入姓名");
            s.Name = Console.ReadLine();
            Console.WriteLine("输入学号");
           
            IStudent id = s;//由于是显式实现,所以必须通过接口实例
            id.StudentId = Console.ReadLine();

            s.Show(s.Name);
            id.Show(id.StudentId);

            Console.ReadLine();
        }
    }
}

 

Guess you like

Origin blog.csdn.net/Kevin_Sun777/article/details/113887683