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)
    {

    }

}

C#继承与接口_第1张图片

你可能感兴趣的:(C#语法基础)