当前位置: 移动技术网 > IT编程>开发语言>.net > Unity3D 接口使用

Unity3D 接口使用

2018年10月07日  | 移动技术网IT编程  | 我要评论

李蕴个人资料,周瑜的妻子是谁,德惠供求世界

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);
        }
    }
}

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网