c#方法扩展

扩展方法能够向现在的类添加方法,但是不需要键新的派生类,重新编译,或是修改原始类就能完成的方法

using System;

namespace 编码练习
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    class ExtensionMethod
    {
        public static void Main(string[] args)
        {
            var person = new Person()
            {
                Name = "张三",
                Age = 15
            };
       //使用扩展方法 person.SayHello(); Console.ReadKey(); } } }
using System;

namespace 编码练习
{
    //Person方法扩展
    public static class PersonExtension
    {
        public static void SayHello(this Person person)
        {
            Console.WriteLine("{0}说“你好”", person.Name);
        }
    }
}

扩展方法规定类必须是静态类,静态类里面的方法必须是静态方法

猜你喜欢

转载自www.cnblogs.com/jestin/p/11612867.html