一开始,在知乎上看到这样的代码,也认为是通过接口实现的,但是仔细看下其实不然。
1.png
发现这个其实是因为Start、Update函数的缘故,且该类继承自monobehaviour。
下面是我的测试代码:
using UnityEngine;
using System.Collections;
interface TestA
{
void FunA();
}
interface TestB
{
void FunB();
}
public class A:TestA
{
void TestA.FunA()//显式实现接口方法
{
Debug.Log("FunA被调用");
}
}
public class B:TestB
{
public void FunB()//隐式实现接口方法
{
Debug.Log("FunB被调用");
}
}
public class TestInterface : MonoBehaviour {
IEnumerator Start()
{
yield return new WaitForSeconds(1);
Debug.Log("IEnumerator类型Start也会被调用");
A a = new A();
TestA inter_a = new A();
//a.FunA() 不能调用
((TestA)a).FunA();//这样可以
inter_a.FunA();
B b = new B();
TestB inter_b = new B();
b.FunB();
inter_b.FunB();
}
}
2.png
通过结果可以得出以下结论:
1.继承自monobehaviour的类不同形式的Start、Update等只能有同名的一个,类型不必是void,访问修饰符不是必须的
2.接口的显式实现只能通过接口实例调用,接口的隐式实现既可以通过接口实例调用,也可以通过类的实例调用
更多的关于C#接口知识可以参考这个。
网友评论