用静态类扩展类的方法

学到静态类,它有一个比较特殊的功能,就是能扩展其他类的方法:

例如:我们定义了要给Person类,但是用过一段时间后发现,这个类的功能不够了,但是又不想从写(或者与别人合作,不能从写),那用静态类来扩展就是一种方法。

Person类    然后我们写了一个静态类  叫做 PersonPlus,在PersonPlus里,写了一个 PersonSaysorry(this Person p)的静态方法,这里要注意,方法的参数这样写:public static void PersonSaysorry(this Person p)

指向我们想要扩展的类名 ,这样 我们用Person的实例就可以调用 PersonSaysorry(this Person p)方法了,和用Person里的方法一样。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticClass
{
  class Program
{
static void Main(string[] args)
{
  Person p = new Person();
  p.PersonSayHello();
  p.PersonSaysorry();
  Console.ReadKey();
}
}

public class Person
{
  private int _age;

  public int Age
  {
    get { return _age; }
  set { _age = value; }
  }

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

static class PersonPlus
{
  public static void PersonSaysorry(this Person p)
{
  Console.WriteLine("sorry!");
}
}
}

 

posted @ 2017-11-26 14:26  StanK  阅读(352)  评论(0编辑  收藏  举报