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

  • 相关阅读:
    solr部署长命版后继
    reiserfs相关
    sqlite in python
    查看文件系统
    https://wiki.fourkitchens.com/dashboard.action这个技术wiki不错
    gvim菜单显示问题
    linux tips
    solr部署一气呵成版,让你多活两天
    挺好玩的C语句
    hardy ubuntu source list
  • 原文地址:https://www.cnblogs.com/darwen/p/7898953.html
Copyright © 2011-2022 走看看