zoukankan      html  css  js  c++  java
  • 用静态类扩展类的方法

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

    例如:我们定义了要给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!");
    }
    }
    }

  • 相关阅读:
    2019年8月20日 item系列
    变量和字符
    python命名规则
    五大常用算法之贪心算法
    过河卒
    组成三位数
    编码问题
    FatMouse' Trade
    A Boring Game
    螺旋矩阵
  • 原文地址:https://www.cnblogs.com/darwen/p/7898953.html
Copyright © 2011-2022 走看看