接口:
一组只有成员方法声明没有方法体的方法集
接口中可写的内容:方法、属性、索引器、事件
要点:类似于类的定义格式,只是以interface作为定义符
格式
[访问修饰符] interface 接口名 { }
注意事项:
接口中声明的方法都是默认public的,不能自定义访问级别
一个类可以实现多个接口,一个接口也可以被多个类调用
实现原则:
实现的方法必须在接口中的原型定义保持一致
必须实现接口中的所有成员方法
脚本Test02
interface Test02
{int years { get; set; }
void Oper();
}
脚本Test01
//隐式接口:
public class Test01 : Test02
{
int Test02Year;
public int years
{
get => Test02Year;
set => Test02Year = value;
}void Test02.Oper()
{
}
}
接口回调
脚本Test02:
interface Test02
{
int years { get; set; }
void Oper();
}
脚本Test01:
public class Test01 : Test02
{
int Test02Year = 10;
public int years
{
get => Test02Year;
set => Test02Year = value;
}
void Test02.Oper()
{
}
}
program
public class ProGram : MonoBehaviour
{
void Start()
{
Test01 t1 = new Test01();
//Test02 t2 = t1;
//Debug.Log(t2.years);
Debug.Log((t1 as Test01).years);
}
}
输出结果为10;
例子:
public static void Main(String[] args)
{
Speak speak = new Speak(); //speak.Bellow() error
(speak as IHello).Bellow(); // 不安全
//原因:有可能出现空指针异常
IHello ih = speak as IHello;
if(ih!=null)
{
ih.Bellow();//安全
}
}