c # extension method

Extension methods can be added to the current class method, but does not require key new derived class, recompile, or modify the original class method can be done

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 
            }; 
       // use the extension method person.SayHello (); the Console.ReadKey (); } } }
the using the System; 

namespace encoding exercise 
{ 
    // the Person method extends 
    public  static  class PersonExtension 
    { 
        public  static  void the SayHello ( the this the Person Person) 
        { 
            Console.WriteLine ( " {0} to say" hello " " , person.Name); 
        } 
    } 
}

Extension method specified class must be a static class inside a static class method must be a static method

Guess you like

Origin www.cnblogs.com/jestin/p/11612867.html