当前位置:首页 > Windows程序 > 正文

C#接口实例详解

2021-05-24 Windows程序

介绍 C#中的接口提供了一种实现运行时的多态。通过接口可以使用相同接口的引用来访问实现相同接口的不同类的方法,,其实是使用虚方法通过相同的引用调用相同基础的不同的类。在开始前先使用简单的短类例子来解释接口的概念,下面的简短的例子显示接口的样子。
P1.cs
程序代码:
class Demo {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }     }
    interface abc {     }

输出:

Hello Interfaces  

编译运行上面的程序运行程序并显示出期望的结果。这段程序包含一个Demo类程序入门Main()方法中打印“Hello Interfaces”。在上面的程序中还定义了接口abc。abc接口是空的,可以在接口中添加一些元素。
P2.cs
程序代码:
class Demo {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }     }
    interface abc {         int x;     }

输出:

P2.cs(11,3): error CS0525: Interfaces cannot contain fields  

错误!在C#的接口中不能包含字段例如变量。上面的程序在接口abc中声明了一个整型变量x。编译将会出错。
P3.cs
程序代码:
class Demo {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }     }
    interface abc {         void xyz() {             System.Console.WriteLine("In xyz");         }     }

输出:

P3.cs(11,8): error CS0531: ‘abc.xyz()‘: interface members cannot have a definition  

这次在接口中定义了xyz()方法C#编译器发现了错误。这说明在接口中成员不能有定义。也就意味着如果在接口abc中仅仅只有方法的声明编译器将认为正确?
P4.cs
程序代码:
class Demo {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }     }
    interface abc {         void xyz();     }

输出:

Hello Interfaces  

上面的程序编译运行正常产生期望的输出结果。最后编译成功。在C#的接口中仅仅包含方法的定义。现在看看方法的作用。
接口是类实现的规范。也就是说接口规定了方法的原型并有类来实现接口所定义的方法原型。
因此在类Demo和接口abc结合在一起。

P5.cs
程序代码:
class Demo : abc {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }     }
    interface abc {         void xyz();     }

输出:

P4.cs(1,7): error CS0535: ‘Demo‘ does not implement interface member ‘abc.xyz()‘ P4.cs(11,8): (Location of symbol related to previous error)  

在上面的代码中Demo和接口abc通过“demo : abc”联系在一起,通常对于这个结合有一点小的误会。类Demo需要负责定义接口abc中定义的方法原型。因此在上面代码中的Demo没有实现abc接口中定义的xyz的方法,上面的代码出错。为了修正问题,类Demo必须实现接口abc中定义的方法原型xyz。看下面的程序代码。
P6.cs
程序代码:
class Demo : abc {         public static void Main() {             System.Console.WriteLine("Hello Interfaces");         }
        void xyz() {             System.Console.WriteLine("In xyz");         }     }
    interface abc {         void xyz();     }

输出:

a.cs(1,7): error CS0536: ‘Demo‘ does not implement interface member ‘abc.xyz()‘.‘Demo.xyz()‘ is either static, not public, or has  the wrong return type. a.cs(16,8): (Location of symbol related to previous error) a.cs(7,8): (Location of symbol related to previous error)  

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70137.html