C#继承与接口

继承: 基类与派生类,基类有的,派生类就有
接口:抽象的某种功能,你要了就得实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestInterface : MonoBehaviour
{
    void Start()
    {
        Xiaojie xiaojie = new Xiaojie("小洁", 25);
        Luosi luosi = new Luosi("罗斯", 28);
        PaoYe paoYe = new PaoYe("泡爷", 34);
        Debug.Log("xiaojie.DoSomething:" + xiaojie.DoSomething("出品UI,打造精品"));
        Debug.Log("luosi.DoSomething:" + luosi.DoSomething("abdfsasda"));
        CCC cCC = new CCC("444") { PPP = "ASDASF" };
        Debug.Log("cCC.PPP:" + cCC.PPP);
        IDoSomething lsq = luosi;
        lsq.DoSomething("彩色a");
        paoYe.FeatAnim("鱼");
        xiaojie.FeatAnim("猫");
        luosi.FeatAnim("狗");
       // IDoSomething paoyee = (IDoSomething)paoYe;  // 不具备转换关系,直接强转是会报错的
        IDoSomething paoyee = paoYe as IDoSomething;//使用as  可以避免转换报错,如果不具备转换关系,则将对象目标转为null.

        if (paoyee != null) paoyee.DoSomething("泡泡爷爷");
    }
}

public class CCC
{
    public string PPP; //{ get; set; }
    public CCC(string SSS)
    {
        PPP = SSS;
    }
}


public interface IAnim
{
    void FeatAnim(string animname);

}
public interface IDoSomething : IAnim
{
    int DoSomething(string thing);
}

public class Employee : IAnim
{
    protected string Name { get; set; }
    int Age { get; set; }

    public Employee(string name, int age)
    {
        Name = name;
        Age = age;
        Debug.Log(string.Format("我的名字是{0},我{1}岁", Name, Age));
    }

    public void FeatAnim(string animname)
    {
        Debug.Log(Name + "养" + animname);
    }
}

public class Xiaojie : Employee, IDoSomething
{

    public Xiaojie(string name, int age) : base(name, age)
    {

    }
    public int DoSomething(string thing)
    {
        Debug.Log(thing);
        return thing.Length;
    }


}

public class Luosi : Employee, IDoSomething
{
    public Luosi(string name, int age) : base(name, age)
    {

    }
    public int DoSomething(string thing)
    {
        int aaa = 0;
        foreach (char item in thing)
        {
            Debug.Log(item);
            if (item == 'a') aaa++;
        }
        return aaa;
    }

}

public class PaoYe : Employee
{
    public PaoYe(string name, int age) : base(name, age)
    {

    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值