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!");
    }
    }
    }

  • 相关阅读:
    JavaScript (new)创建一个对象的过程
    我所理解的promise的then方法
    promise与async和await的区别
    JS Promise实例 then()方法
    电脑上不去网
    es6----set map应用场景
    ES6新特性一览
    es6继承
    es6中class类的全方面理解(一)
    时间处理金字教程
  • 原文地址:https://www.cnblogs.com/darwen/p/7898953.html
Copyright © 2011-2022 走看看