首页 > 其他 > 详细

接口的学习

时间:2019-06-19 16:27:34      阅读:98      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodInterface
{
    class CA
    {
        public string Name;
        public int Age;
    }
    class CB
    {
        public string First;
        public int Last;
    }
    class Program
    {
        static void PrintInfo(CA fg)
        {
            Console.WriteLine("Name:{0},Age{1}", fg.Name, fg.Age);
            Console.ReadKey();
        }
        static void Main()
        {
            //没有接口,这里的函数只能是CA,如果加入接口可以实现CA、CB互换。
            CA a = new CA();
            PrintInfo(a);
        }
    }
    /// <summary>
    /// 声明一个接口,包含两个方法,这两个方法都返回string
    /// 接口需要被实现,实现后才能用
    /// </summary>
    interface Iinfo
    {
        string GetName();
        string GetAge();
    }

    class CA1 : Iinfo
    {
        public string Name;
        public int Age;
        //实现接口
        public string GetName()
        { return Name; }
        public string GetAge()
        { return Age.ToString();}
    }
    class CB1 : Iinfo
    {
        public string First;
        public string Last;
        public double Personal;
        //实现接口
        public string GetName() { return First + "" + Last; }
        public string GetAge() { return Personal.ToString(); }
    }
    class Program1
    {
        //使用接口
        static void PrintInfo1(Iinfo Iin)
        {
            Console.WriteLine("Name:{0},Age{1}", Iin.GetName(), Iin.GetAge());
            
        }
        static void Main()
        {
            CA1 a = new CA1() { Name = "john doe",Age=35 };
            CB1 b = new CB1() { First ="jane",Last ="doe",Personal=33};
            //对象的引用能自动转换为他们实现接口的引用,自动找到
            PrintInfo1(a);
            PrintInfo1(b);
        }
    }
}

 

接口的学习

原文:https://www.cnblogs.com/JazzYan/p/11051700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!