Unity3D 接口使用

C#怎么实现多继承?

说起多继承,首先大家可以想想这个问题:你知道在C#中怎么实现多继承吗?

主流的答案无非2种。

答案一:用接口啊,一个类可以继承自多个接口的。
答案二:C#不支持多继承,C++才支持多继承,多继承会让代码变得很乱,因此微软在设计C#的时候放弃了多继承。

先说说什么是真正意义的多继承。真正的多继承应该是像C++那样的,而不是说像在C#里面一个类继承了多个接口就叫多继承。在C#中,如果一个类实现了多个接口,那么要为每个接口写实现,如果接口被多个类继承,那么就会有重复的代码,这显然是无法接受的。

然而C++那样的多继承也确确实实给编码带来了很大的麻烦,我也相信微软真的是因为意识到了多继承的不合理之处才在C#中摈弃了这个特性。其他的在这里就不多说了,请看案例

案例:

假如我们要写一个背包系统,背包里自然有很多物品,那我们该怎么识别 我们当前使用的是什么物品呢?

笔者在这里使用接口来简单实现一个背包

 

IA.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace abc
{
    public interface IA
    {
        void ItemFunction();
    }

}

 

HpScript.cs

using UnityEngine;
using abc;
public class HpScript : MonoBehaviour, IA
{
    public void ItemFunction()
    {
        ItmeDrugFunction();
    }

    void ItmeDrugFunction()
    {
        Debug.Log("Hp");
    }
}

Mpscript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class Mpscript : MonoBehaviour, IA
{
    void IA.ItemFunction()
    {
        ItmeDrugFunction();
    }
    void ItmeDrugFunction()
    {
        Debug.Log("Mp");
    }
}

SwordScript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class SwordScript : MonoBehaviour, IA
{
    void IA.ItemFunction()
    {
        ItmeDrugFunction();
    }
    void ItmeDrugFunction()
    {
        Debug.Log("Swrod");
    }
}

Backpack.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class Backpack : MonoBehaviour {

    public GameObject itme;
    internal Transform itmeChilld;
    void Start () {
      
        if(itme != null && itme.transform.GetChild(2) != null) //如果当前节点不为空并且它子节点第二个元素也不为空
        {
            itmeChilld = itme.transform.GetChild(2);
            itmeChilld.GetComponent<IA>().ItemFunction();    //使用接口访问
            Debug.Log("Name : " + itmeChilld.name);
        }
    }
}

我们可以测试访问以下,看看是不是我们想要的结果

经过测试 是我们想要的结果,就这样一个简单的背包就做好了。喜欢的请点个赞哦!

posted @ 2018-10-05 11:47  涂涂毅儿  阅读(6232)  评论(0编辑  收藏  举报