Welcome

首页 / 软件开发 / C# / C#语法练习(15): 接口

C#语法练习(15): 接口2011-09-22 博客园 万一接口只声明、无实现、不能实例化;

接口可包含方法、属性、事件、索引器, 但无字段;

接口成员都是隐式的 public, 不要使用访问修饰符;

类、结构和接口都可以继承多个接口;

继承接口的类必须实现接口成员, 除非是抽象类;

类实现的接口成员须是公共的、非静态的.

入门示例:

using System;

interface MyInterface
{
int Sqr(int x);
}

class MyClass : MyInterface
{
public int Sqr(int x) { return x * x; }
}

class Program
{
static void Main()
{
MyClass obj = new MyClass();
Console.WriteLine(obj.Sqr(3)); // 9

MyInterface intf = new MyClass();
Console.WriteLine(intf.Sqr(3));

Console.ReadKey();
}
}