接口只包含方法、委托或事件的签名。方法的实现是在实现接口的类中完成的,如下面的示例所示:
| 复制代码 |
---|
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
} |
备注
示例
下面的示例演示了接口实现。在此例中,接口 IPoint
包含属性声明,后者负责设置和获取字段的值。Point
类包含属性实现。
| 复制代码 |
---|
// keyword_interface_2.cs
// Interface implementation
using System;
interface IPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
class Point : IPoint
{
// Fields:
private int _x;
private int _y;
// Constructor:
public Point(int x, int y)
{
_x = x;
_y = y;
}
// Property implementation:
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
static void Main()
{
Point p = new Point(2, 3);
Console.Write("My Point: ");
PrintPoint(p);
}
} |
输出
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
1.9 接口
-
3.4.5 接口成员
-
4.2.4 接口类型
-
10.1.2.2 接口实现
-
11.2 结构接口
-
13 接口
请参见