(C#)扩展方法

意图在不修改类的情况下添加方法:

定义一个静态类,再定义一个静态方法。

using System;

namespace ExtendMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person("Allen",19);
            person.ShowName();//输出结果My Name Is Allen
            person.ShowAge();//输出结果My Age Is 19
            Console.ReadLine();
        }
    }

    public class Person
    {
        public String Name { get; set; }
        public int Age { get; set; }

        public Person(String name,int age)
        {
            this.Name = name;
            this.Age = age;
        }

        public void ShowName()
        {
            Console.WriteLine($"My Name Is {this.Name}");
        }
    }

    public static class PersonExtend
    {
        public static void ShowAge(this Person person)
        {
            Console.WriteLine($"My Age Is {person.Age}");
        }
    }
}

 

扩展接口方法:

using System;

namespace ExtendInterfaceMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            ICalculateAble calculate = new A();
            calculate.Addition(2, 3);//输出结果5
            calculate.Subtraction(2, 3);//输出结果-1
            Console.ReadLine();
        }
    }

    public interface ICalculateAble
    {
        void Addition(int a, int b);
    }

    public class A : ICalculateAble
    {
        //只写了加法
        public void Addition(int a,int b)
        {
            Console.WriteLine(a + b);
        }
    }

    public static class InterfaceExtend
    {
        //扩展减法
        public static void Subtraction(this ICalculateAble calculate,int a,int b)
        {
            Console.WriteLine(a - b);
        }
    }
}

 

posted @ 2021-05-30 14:36  30殺大魔王  阅读(60)  评论(0)    收藏  举报