接口(C# 参考)
来源:互联网 发布:vb中变量名的命名规则 编辑:程序博客网 时间:2024/06/09 23:46
接口只包含方法、委托或事件的签名。方法的实现是在实现接口的类中完成的,如下面的示例所示:
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();
}
}
...{
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();
}
}
接口可以是命名空间或类的成员,并且可以包含下列成员的签名:
-
方法
-
属性
-
索引器
-
事件
一个接口可从一个或多个基接口继承。
当基类型列表包含基类和接口时,基类必须是列表中的第一项。
实现接口的类可以显式实现该接口的成员。显式实现的成员不能通过类实例访问,而只能通过接口实例访问,例如:
有关显式接口实现的更多详细信息和代码示例,请参见显式接口实现(C# 编程指南)。
下面的示例演示了接口实现。在此例中,接口 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);
}
}
// 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);
}
}
输出
My Point: x=2, y=3
- 接口(C# 参考)
- 接口(C# 参考)
- switch(C# 参考)
- base(C# 参考)
- abstract(C# 参考)
- partial(C# 参考)
- ref(C# 参考)
- sealed(C# 参考)
- virtual(C# 参考)
- const(C# 参考)
- extern(C# 参考)
- #region(C# 参考)
- #region(C# 参考)
- ref(C# 参考)
- base(C# 参考)
- enum(C# 参考)
- enum(C# 参考)
- as(C# 参考)
- Spring by Thomas Nash
- first day
- 搜索局域网内机算机(机器名、IP。MAC地址)
- flash+asp.net上传文件,显示进度条
- SAP系统的开发语言--ABAP简介
- 接口(C# 参考)
- showModalDialog和showModelessDialog用法
- 有状态会话BEAN例子
- 中移动飞信战略初步曝光 明日正式商用
- 无效过程调用或参数
- ActionScript3.0 基础知识
- VBScrip运行时错误 收集
- [转载]AT&T 汇编简介
- 同时安装sql2000和sql2005,经验点滴