Interface in C #

xiaoxiao2021-03-06  63

The interface combines a set of public methods and properties to encapsulate a collection of specific functions. The interface can be implemented through the class, so that all properties and methods of the interface are supported.

The interface can only be defined for methods and properties, and cannot be implemented, can only be implemented by a class that supports it. Members in the interface cannot be modified with access, such as public, private, its member defaults to public

Define the interface is relatively simple

Public Interface ImyInterface

{

Void dosomething (); // method member

INT myattribute // member member

{

Get; // You can only define this property is read-only.

SET;

}

}

The interfaces and abstract classes are similar, but a class can only be derived from an abstract class, but n interfaces can be implemented.

For example to explain it.

There are two abstract classes, car and train, car and train

There are still many classes, such as bus, truck, etc.

Bus, trucks are derived from trains

In Car, Train demonstrates some main features of the car and the train.

Naturally, their derived class has such features.

But the bus under the car, the passenger cars under the train can take guests, so these two classes can achieve an interface with the functions of ride, and trucks and trucks can share a portable interface with carrier goods.

A class supports a pick, you must implement all of it

Interface ImyInterface

{

Void Dosomething ();

Void doelsething ();

}

Class myclass: ImyInterface

{

void iMyinterface.dosomething ()

{

Console.WriteLine ("1");

}

Public Virtual VoidoelSethiing ()

{

Console.writeLine ("2");

}

} class myclass2: myclass {public override void doelsething () {console.writelint ("3");}} The above defined an interface ImyInterface, MyClass implemented this interface, so that the class MyClass2 derived from Myclass is also the default support. This interface also inherits the implementation of the method, in MyClass2, can also rewrite the DOELSETHING method. But this is premised. That is the doelsething method is implicitly implemented by myclass classes. Implicit implementation is only necessary to match the return value and method signature. Such methods can be modified using Guanjian Vritual and Abstract, and can call Class Obj = new myclass (); Obj.DoElSethiing (); Obj.DoElSethiing (); and the first method DOSMETHING is explicitly executed. It can only be called by the reference variable of the interface. Moreover, the derived class does not inherit this method, so the above myclass2 class also adds an implementation of this method because it inherits myclass and supports this interface.

转载请注明原文地址:https://www.9cbs.com/read-85449.html

New Post(0)