Copy codeThe Code is as follows: // <summary>
/// Interface
/// Differences from abstract classes:
/// 1. abstract can have specific methods and abstract methods (there must be an abstract method). interface has no method implementation.
/// 2. abstract can have constructor and destructor, but the interface does not work.
/// 3. A class can implement multiple interfaces, but can inherit only one abstract
/// Features:
/// The interface member is implicitly public, so no modifier is added.
/// You cannot directly create an interface instance, for example, IPerson xx = new IPerson () // error
/// </Summary>
Public interface IPerson
{
String Name {get; set;} // feature
DateTime Brith {get; set ;}
Int Age (); // Function Method
}
Interface IAdderss
{
Uint Zip {get; set ;}
String State ();
}
Copy codeThe Code is as follows: // <summary>
/// Interface implementation interface
/// </Summary>
Interface IManager: IPerson
{
String Dept {get; set ;}
}
/// <Summary>
/// Implement multiple interfaces
/// Which interface to implement must be written into all members of the Full Implementation!
/// </Summary>
Public class Employee: IPerson, IAdderss
{
Public string Name {get; set ;}
Public DateTime Brith {get; set ;}
Public int Age ()
{
Return 10;
Throw new NotImplementedException ();
}
Public uint Zip {get; set ;}
Public string State ()
{
Return "alive ";
}
}
Copy codeThe Code is as follows: // <summary>
/// Rewrite interface implementation:
/// As follows, the class Employer implements IPerson, in which the method Age () is marked as virtual, so the class inherited from Employer can override Age ()
///
/// </Summary>
Public class Employer: IPerson
{
Public string Name {get; set ;}
Public DateTime Brith {get; set ;}
Public virtual int Age ()
{
Return 10;
}
}
Public class work: Employer
{
Public override int Age ()
{
Return base. Age () + 100; // where base is the parent class
}
}
Implementation, object and instance:
Copy codeThe Code is as follows: # region # interface
Employee eaji = new Employee ()
{
Name = "aji ",
Brith = new DateTime (1991,06, 26 ),
};
# Endregion
# Region # forced conversion of interfaces
IPerson ip = (IPerson) eaji; // you can use an instance to forcibly convert an interface instance to access its members,
Ip. Age ();
DateTime x = ip. Brith;
// You can also write it as follows:
IPerson ip2 = (IPerson) new Employee ();
// But sometimes it is not safe. We usually use is and as to force conversion:
If (eaji is IPerson)
{
IPerson ip3 = (IPerson) eaji;
}
// But is not very efficient, it is best to use:
IPerson ip4 = eaji as IPerson;
If (ip4! = Null) // when using as, if the class implementing ip4 does not inherit IPerson, null is returned.
{
Console. WriteLine (ip4.Age ());
}
# Endregion