C # Advanced Road --10.C # Interface

C # Advanced road --10. C # Interface 

basis:

Interface Interface

Interface is an abstract method, if different classes the same way, then you should consider using the interface.

Interface Name: Always preceded by a capital letter I

Interface method body does not appear, there is no modifier class provides methods to achieve body and assign some of the modifiers, if the class does not implement this method will compile error.

 

Interface Example: ILogger defined text log output interface

  1. using System;
  2. public interface ILogger
  3. {
  4. void Log(string Info);
  5. }
  6. public class TextLogger : ILogger
  7. {
  8.  public void Log(string Info)=> Console.Write("In base Logger");
  9. }

 

The definition of a has a Log () method ILogger interface. And there is a known implementation of the interface ILogger of TextLogger class, a text log output.

 

Advanced:

 

interface

1, an interface equivalent to an abstract class, but it does not contain any implementation.

2, the interface of each method must be implemented in a derived class.

3, sometimes the interface class can be seen as a mold, a category which indicates what the provider.

4, the interface body limited method, indexer, property declarations.

5, the interface can not contain fields, constants, etc., and constructors.

6, the interface members are implicitly public, if it is explicitly specified access level, a compiler error occurs.

7, can not be achieved by any method, property or index in the interface.

8, when the specified method, given only the return type, name and parameter list, and then terminated by a semicolon.

9, implementation of the interface and implementation inheritance syntax, like all colon ":"

10, interface methods can not be overridden, can only be achieved.

C # in multiple implementation of the interface, to make up for C # only single inheritance, multiple inheritance can not shortcomings.

If there are two interfaces in the same signature can be used "interface name . Method name" manner explicitly implement the interface.

A class to implement an interface, you must write code that implements the interface for all members of the base and derived interface.

 

C#接口中的默认方法

接口示例:扩展ILogger接口并在其中添加更多信息

 

  1. public interface ILogger
  2. {
  3. void Log(string info);
  4. void Log(string typeofInformation,string info)

}

当接口被多个类使用,根据使用此接口的位置在实现中进行这些更改代价很大。实现这个方法就需要使用C#8接口中的默认方法。

在C#中,类不允许多重继承,接口也只在有限的范围内进行多重继承,而且不包含状态。

此时为了在应用程序中使用此接口,需要改变main方法,要访问默认接口方法,必须将其转型成接口。

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.            ILogger _logger = new TextLogger();//将类对象作为接口进行实现。
  6.            _logger.LogInfo("Test","test"); // It will call the Default method of the interface
  7.         } 
  8.       }}

注意:要访问默认接口方法,必须将其转型成接口。只有将类作为接口进行上下文处理时,接口默认方法才有效。否则如下图,类创建对象时,默认方法无法使用。

注意:C# 默认接口会产生多重继承问题,即钻石问题。

 

 

即在main中没有将类作为接口进行处理,则找不到对应接口方法。

 

 

接口语法要素

接口语法已经经过扩展,可接受下面列出的新关键字。例如,你可以在接口中编写一个私有方法,代码仍然可以通过编译并正常工作。

方法体或索引器、属性、事件访问器

private、protected、internal、public、virtual、abstract、override、sealed、static、extern\\t

静态字段

静态方法、属性、索引器和事件

具有默认访问权限的显式访问修饰符是public的

Override修饰符

不允许出现:实例状态、实例字段、实例自动属性

 

 

示例

C#接口默认方法中钻石问题的解决

  1. Interface First
  2. {
  3.     void WritetoConsole() => Console.Write("In First");
  4. }
  5.  
  6. interface Second:First{
  7.  void First.WritetoConsole()=>Console.Write("In Second");
  8. }
  9.  

interface Third:First{

  void First.WritetoConsole()=>Console.Write("In Third");

}

 

class FinalClass : Second,Third

{

}

编译出现错误:接口成员' First.WritetoConsole()'没有最具体的实现。

 “Second.First.WritetoConsole()”和“ Third.First.WritetoConsole()”都不是具体的。

为了解决错误本身所描述的这个问题,我们需要在执行时提供最具体的覆盖。

Dotnet设计团队通过在运行时调用最具体的覆盖方法来解决钻石问题:“接口成员的类实现应该总是胜过接口中的默认实现,即使它是从基类继承的。只有当类没有提供具体的实现时,才考虑使用默认实现”。

  1. using System;
  2. interface First
  3. {
  4.     void WritetoConsole() => Console.Write("In First");
  5. }
  6.  
  7. interface Second:First{
  8.  void First.WritetoConsole()=>Console.Write("In Second");
  9. }

 

interface Third:First{

  void First.WritetoConsole()=>Console.Write("In Third");

}

 

class FinalClass : Second,Third

{

  void First.WritetoConsole(){

  Console.Write("From Final class");

}

}

注意:在覆盖的方法中不允许出现访问修饰符。这里关键字virtual和abstract可以没有,不过有对编译后的代码也没有任何影响。

C#8.0之后可以在接口中使用修饰符private,protected,internal,public和virtual。

所有默认接口的方法都是virtual,可以自主设置为private或sealed。

没有正文的所有成员在默认情况下都被视为抽象,则必须在具体类中实现。

接口语法现在可以接受以下关键字:protected、internal、public和virtual。C#8.0之后可以在接口中使用修饰符private。

默认情况下,接口方法是virtual的,除非使用了sealed或private修饰符。

类似的,没有方法体的接口成员默认是abstract的,则必须在具体类中实现。

  1. using System;
  2. interface IInterfaceModifiers
  3. {
  4.   //By Default default method is private
  5.   virtual void DefaultMethod()=>Console.WriteLine("Default method");
  6.   //Private Default Method
  7.   private void privatedefaultmethod()=>Console.WriteLine(" private Default method");
  8.   //Protected Default Method
  9.   protected void ProtectedDefaultMethod()=>Console.WriteLine(" protected Default method");

  // Public Default Method

  public void PublicDefaultMethod()=>Console.WriteLine(" public Default method");

  virtual void VirtualDefaultMethod()=>Console.WriteLine("Virtual Default method");

  abstract void AbstractDefaultMethod();

}

class InterfaceModifierDemo : IInterfaceModifiers

  public void AbstractDefaultMethod() => Console.WriteLine("Abstract virtual method");

}

 

//main方法中

namespace DeaultInterfaceDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            IInterfaceModifiers i= new InterfaceModifierDemo();

            i.AbstractDefaultMethod();

            i.DefaultMethod();

            i.PublicDefaultMethod();

            i.VirtualDefaultMethod();

        }

   }

}

 

//控制台输出:

  1. Abstract virtual method
  2. Default method
  3. public Default method
  4. Virtual Default method

//当我们创建一个protected方法时,它在继承接口中可用,而不是实现类。

//默认情况下,接口的成员是abstract,这使得实现类必须正确实现它们。

 

 来源:

https://blog.csdn.net/mzl87/article/details/94626205

https://blog.csdn.net/weixin_33755557/article/details/89129382

https://www.cnblogs.com/LagoOrLY/p/10318214.html

Guess you like

Origin www.cnblogs.com/PaulTsao/p/11486140.html