zoukankan      html  css  js  c++  java
  • 接口(C# 参考)

    接口只包含方法、属性、事件或索引器的签名。 实现接口的类或结构必须实现接口定义中指定的接口成员。 在下面的示例,类 ImplementationClass必须实现一个不具有参数并返回 void 的名为 SampleMethod 的方法。

    示例

     1 interface ISampleInterface
     2 {
     3     void SampleMethod();
     4 }
     5 
     6 class ImplementationClass : ISampleInterface
     7 {
     8     // Explicit interface member implementation: 
     9     void ISampleInterface.SampleMethod()
    10     {
    11         // Method implementation.
    12     }
    13 
    14     static void Main()
    15     {
    16         // Declare an interface instance.
    17         ISampleInterface obj = new ImplementationClass();
    18 
    19         // Call the member.
    20         obj.SampleMethod();
    21     }
    22 }

    接口可以是命名空间或类的成员,并且可以包含下列成员的签名:

    • 方法

    • 属性

    • 索引器

    • 事件

    一个接口可从一个或多个基接口继承。

    当基类型列表包含基类和接口时,基类必须是列表中的第一项。

    实现接口的类可以显式实现该接口的成员。 显式实现的成员不能通过类实例访问,而只能通过接口实例访问。

    示例

    下面的示例演示了接口实现。 在此示例中,接口包含属性声明,类包含实现。 实现 IPoint 的类的任何实例都具有整数属性 x 和 y。

     1 interface IPoint
     2 {
     3    // Property signatures:
     4    int x
     5    {
     6       get;
     7       set;
     8    }
     9 
    10    int y
    11    {
    12       get;
    13       set;
    14    }
    15 }
    16 
    17 class Point : IPoint
    18 {
    19    // Fields:
    20    private int _x;
    21    private int _y;
    22 
    23    // Constructor:
    24    public Point(int x, int y)
    25    {
    26       _x = x;
    27       _y = y;
    28    }
    29 
    30    // Property implementation:
    31    public int x
    32    {
    33       get
    34       {
    35          return _x;
    36       }
    37 
    38       set
    39       {
    40          _x = value;
    41       }
    42    }
    43 
    44    public int y
    45    {
    46       get
    47       {
    48          return _y;
    49       }
    50       set
    51       {
    52          _y = value;
    53       }
    54    }
    55 }
    56 
    57 class MainClass
    58 {
    59    static void PrintPoint(IPoint p)
    60    {
    61       Console.WriteLine("x={0}, y={1}", p.x, p.y);
    62    }
    63 
    64    static void Main()
    65    {
    66       Point p = new Point(2, 3);
    67       Console.Write("My Point: ");
    68       PrintPoint(p);
    69    }
    70 }
    71 // Output: My Point: x=2, y=3

    作者:耑新新,发布于  博客园

    转载请注明出处,欢迎邮件交流:zhuanxinxin@aliyun.com

  • 相关阅读:
    101个微软提供的Visual Studio 2005示例[转贴]
    验证码的三种做法[纯数字][纯汉字][字母\数字\汉字混合]C#
    XML做数据库操作之 我浑了
    推荐几个用得上且免费的 .NET控件
    一些怪得你没想过的软件,大多还是有用的!
    ASP.NET 程序中常用的三十三种代码[转载与 aspcool]
    js入门系列演示·数组
    AJAX!?!入门之道
    js入门·移动窗体/弹出提示
    javascript入门系列演示·函数的定义以及简单参数使用,调用函数
  • 原文地址:https://www.cnblogs.com/Arthurian/p/5964453.html
Copyright © 2011-2022 走看看