C# study notes interface

interface

The interface in C# is syntactically similar to an abstract class. It defines a number of abstract methods, attributes, indexers, and events to form a collection of abstract members. Each member usually reflects certain things. Aspect function. An interface is essentially an agreement on certain functions or features.
The usefulness of the interface in the program is mainly reflected in the following aspects:

  • The same behavior of unrelated classes can be achieved through interfaces, without the need to consider the hierarchical relationship between these classes.
  • Through the interface, you can specify the methods that multiple classes need to implement.
  • Through the interface, you can understand the interactive interface of the object without knowing the class corresponding to the object.

Define the interface

Define the interface using interfacekeywords. There can be multiple members in the interface.
The members of an interface must be abstract methods, properties, events, or indexers, and these abstract members have no implementation body. An interface cannot contain constants, fields, operators, constructors, static constructors, or nested types, nor can it include static members of any type.
All interface members are implicitly publicly accessible, that is, implicitly yes public. However, newany modifiers other than those cannot be used in interface member declarations . However, the interface itself can take modifiers, such as public, interface. According to coding conventions, the names of interfaces all start with a capital letter I. example:

public interface IStringList
{
    
    
	void Add(string s);
	int Count{
    
    get;}
	string this[int index]{
    
    get; set;}
}

This interface contains a method, a property, and an indexer.


An interface can inherit from one or more base interfaces (parent interfaces). example:

interface IMyInterface:IBase1, IBase2
{
    
    
	void MethodA();
	void MethodB();
}

The sub-interface will inherit all the properties and methods in the parent interface. You can also use newmodifiers to hide members in the parent interface.
For example, the following definition System.Collections.IList:

public interface IList:ICollection, IEnumerable
{
    
    
	bool IsFixedSize{
    
    get;}
	bool IsReadOnly{
    
    get;}
	object this[int index]{
    
    get; set;}
	int Add(object value);
	void Clear();
	bool Contains(object value);
	int IndexOf(object value);
	void Insert(int index, object value);
	void Remove(object value);
	void RemoveAt(int index);
}	

Implement the interface

The declaration of the interface only provides abstract methods, which is equivalent to a set of protocols in the early stage of program development. To specifically realize the functions specified by the interface, a certain class needs to write statements for the abstract methods in the interface and define the actual method body. .
Interfaces can be implemented by classes or structs. The following is the format of using a class to implement an interface:

class 类名:[父类,] 接口, 接口, ..., 接口 
{
    
    
	...
}

When a class implements an interface, pay attention to the following issues:

  • In the declaration part of the class, use a colon ( :) to indicate its parent class and the interface to be implemented, where the parent class must be placed in front of the interface name. If the parent class is omitted, the implicit parent class is System.Object.
  • If a class implements an interface, it must be able to find the members corresponding to each member of the interface in the class, and also find all the members of all the parent interfaces of the interface. Of course, such members can be defined in this class or inherited from the parent class of this class.
  • When an abstract class implements an interface, it is also required to provide implementation programs for all members. The abstract class can map interface methods to abstract methods.
  • A class can only have one parent class, but it can implement several interfaces at the same time. When a class implements multiple interfaces, if the interface is understood as a special class, then this class actually obtains multiple parent classes by using the interface, that is, multiple inheritance is realized.
  • Pay special attention to the implicit access control of the abstract methods of the interface public, so the class must use publicmodifiers when implementing methods .

Example:

using System;

namespace ConsoleApp3接口
{
    
    
	interface Runner
	{
    
    
		void run ();
	}
	interface Swimmer
	{
    
    
		void swim ();
	}
	abstract class Animal
	{
    
    
		abstract public void eat ();
	}

	class Person : Animal, Runner, Swimmer
	{
    
    
		public void run () {
    
    
			Console.WriteLine ("run");
		}
		public void swim () {
    
    
			Console.WriteLine ("swim");
		}
		public override void eat () {
    
    
			Console.WriteLine ("eat");
		}
		public void speak () {
    
    
			Console.WriteLine ("speak");
		}
	}

	class TestInterface
	{
    
    
		static void m1 (Runner r) {
    
    
			r.run ();
		}
		static void m2 (Swimmer s) {
    
    
			s.swim ();
		}
		static void m3 (Animal a) {
    
    
			a.eat ();
		}
		static void m4 (Person p) {
    
    
			p.speak ();
		}
		public static void Main (string[] args) {
    
    
			Person p = new Person ();
			m1 (p);
			m2 (p);
			m3 (p);
			m4 (p);

			Runner a = new Person ();
			a.run ();
		}
	}
}

Reference to interface

The interface can be used as a reference type, and the methods in the interface implemented by the class can be accessed through these reference variables. For example: if the Personclass is implemented ISwimmable, you can refer to the Personobject as ISwimmable:

	Person p = new Person();
	ISwimmable s = p;

Similarly, if a method requires an interface as a parameter, you can directly pass in an instance object of a class that implements the interface. The interface as a data type does not need to know the specific class corresponding to the object, but focuses on its interactive interface or function.
An interface may have multiple parent interfaces, and the members in the interface may have the same name. Therefore, when calling the interface members, there may be ambiguity. E.g:

interface IList
{
    
    
	int Count{
    
    get; set;}
}
interface ICounter
{
    
    
	void Count(int i);
}
interface IListCounter : IList, ICounter{
    
    }
class C
{
    
    
	void Test(IListCounter x){
    
    
		x.Count(1);				// Error, Count不明确
		x.Count = 1;			// Error, Count不明确
		((IList)x).Count = 1;	// Ok, 调用IList.Count.set
		((ICounter)x).Count(1);	// Ok, 调用ICounter.Count
	}
}

Show interface member implementation

Sometimes, multiple interfaces have the same signature method (or other members). If a class needs to implement multiple interfaces at the same time, you can use only one method to meet the requirements of each interface. However, in more cases, the meaning of these same signature methods in each interface is not the same, so when the class implements each interface, it is required to display the method in which interface it implements. E.g:

using System;

namespace ConsoleApp3接口
{
    
    
	class InterfaceExplicitImpl
	{
    
    
		static void Main (string[] args) {
    
    
			FileViewer f = new FileViewer ();
			f.Test ();
			((IWindow)f).Close ();

			IWindow w = new FileViewer ();
			w.Close ();
		}
	}
	
	interface IWindow
	{
    
    
		void Close ();
	}
	interface IFileHander
	{
    
    
		void Close ();
	}
	class FileViewer : IWindow, IFileHander
	{
    
    
		void IWindow.Close () {
    
    
			Console.WriteLine ("Window Closed");
		}

		void IFileHander.Close () {
    
    
			Console.WriteLine ("File Closed");
		}

		public void Test () {
    
    
			((IWindow)this).Close ();
		}
	}
}

It can be seen from the above that the display interface member implementation program has different access capability characteristics compared with other members. Because display interface members cannot be called through class instances, in this sense they are private; on the other hand, they can be accessed through an interface instance, in this sense, they are public.

The realization of display interface members mainly serves two purposes:

  • Because it shows that interface members cannot be accessed through the class or structure instance, but only through the interface is allowed. Therefore, it is often used to describe the situation in which only the interface can be accessed.
  • The display interface member implementation program allows the same signature to disambiguate interface members, so that a class or structure can contain members with the same signature but different return types.

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/113965436