c#中的接口

使用IEnumerable统一迭代变量类型

class Program
{
    static void Main(string[] args)
    {
        int[] nums1 = new int[] { 1, 2, 3, 4, 5 };
        ArrayList nums2 = new ArrayList { 1, 2, 3, 4, 5 };
        Console.WriteLine(Sum(nums1));
        Console.WriteLine(Sum(nums2));
        Console.WriteLine(Avg(nums1));
        Console.WriteLine(Avg(nums2));
    }

    static int Sum(IEnumerable nums)
    {
        int sum = 0;
        foreach (var n in nums)
        {
            sum += (int)n;
        }
        return sum;
    }
    static double Avg(IEnumerable nums)
    {
        int sum = 0;
        double count = 0;
        foreach (var n in nums)
        {
            sum += (int)n;
            count++;
        }
        
        return sum/count;
    }

}

c#中的接口_第1张图片

使用接口实现松耦合:手机类为例

class Program
    {
        static void Main(string[] args)
        {
            PhoneUser phoneUser = new PhoneUser(new Ericsson());
            phoneUser.UsePhone();
            
        }   

    }
    class PhoneUser
    {
        private IPhone _phone { get; set; }
        public PhoneUser(IPhone phone)
        {
            _phone = phone;
        }
        public void UsePhone()
        {
            _phone.Dail();
            _phone.PickUp();
            _phone.Send();
            _phone.Receive();
        }
    }

    interface IPhone
    {
        void Dail();
        void PickUp();
        void Receive();
        void Send();
    }
    public class NokiaPhone : IPhone
    {
        public void Dail()
        {
            Console.WriteLine("Nokia calling...");
        }

        public void PickUp()
        {
            Console.WriteLine("Hello!This is NokiaPhone!");
        }

        public void Receive()
        {
            Console.WriteLine("Nokia message ring...");
        }

        public void Send()
        {
            Console.WriteLine("Hello");
        }
    }
    class Ericsson : IPhone
    {
        public void Dail()
        {
            Console.WriteLine("Ericsson calling...");
        }

        public void PickUp()
        {
            Console.WriteLine("Hello!This is Ericsson!");
        }

        public void Receive()
        {
            Console.WriteLine("Ericsson message ring...");
        }

        public void Send()
        {
            Console.WriteLine("Hello Ericsson");
        }
    }

你可能感兴趣的:(C#笔记,c#,开发语言)