Interface接口基本语法
接口定义协定。 实现该协定的 class 或 struct 必须提供接口中定义的成员的实现。 从 C# 8.0 开始,接口可为成员定义默认实现。 它还可以定义 static 成员,以便提供常见功能的单个实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSGDemoCSG009
{
//https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/interfaces/
public delegate void SampleDelegate();
//#csg009-01
//接口声明
interface ISampleInterface
{
//接口可以包含方法
void SampleMethod();
void SampleMethod2();
//接口可以包含属性
string Porperty { get; set; }
//接口可以包含静态字段
static string StaticValue;
//接口可以包含索引器
string this[int i]
{
get;
set;
}
//接口可以包含事件
event SampleDelegate SampleEvent;
}
//#csg009-02
//从C#8.0开始,接口可以定义默认实现
interface ISampleInterface2
{
void DefaultMethod()
{
Console.WriteLine("default implement of interface");
}
}
interface ISampleInterface3
{
void SampleMethod();
void SampleMethod2();
}
//#csg009-03
//继承并实现接口,隐式实现与显示实现
class ImplementationClass : ISampleInterface3
{
//显示实现接口
void ISampleInterface3.SampleMethod()
{
// Method implementation.
}
//隐式实现接口
public void SampleMethod2() { }
static void Main()
{
// Declare an interface instance.
ISampleInterface3 obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
}