zoukankan      html  css  js  c++  java
  • c# 如何扩展系统内置类(C#3.0)

    c#3.0(VS2008)支持在任何类型上扩展生成自定义的方法。比如说想在string类型的对象里面多一个ToInt32(),来方便的将字符转换成整形。

    在实现的过程中的关键字为static和this

    下面我们来做一个在string类型中新建一个ToInt32的自定义方法

    View Code
    public static class Extensions//注意静态    {
    publicstaticint ToInt32(this string INPUT)// 注意THIS关键字 {
    return Convert.ToInt32(INPUT);
    }
    }

    那么在使用string的对象的时候,会多出一个ToInt32的方法

    View Code
    static void Main(string[] args)
    {
    string a ="321";
    int b = a.ToInt32();
    Console.ReadKey();
    }

    既然可以扩展.net的内置类型,那能不能扩展自定义类型呢。

    View Code
    public class A//先定义A类
    {
    }

    public static class Extensions
       {
    public static int ToInt32(this string In) {
    return Convert.ToInt32(In);
    }
    //为A新增一个ExtensionMethod方法
    public static string ExtensionMethod(this A a) {
    return "this is extension method";
    }
    }

    在使用A的对象的时候,会多出一个ExtensionMethod方法

    View Code
    staticvoid Main(string[] args)
    {
    string a ="1";
    int b = a.ToInt32();
    A c
    =new A();
    string d = c.ExtensionMethod();
    Console.ReadLine();
    }

    C#3.0的这个新特性意味着我们可以肆无忌惮的扩展我们想要扩展的类型,即便这个类型是从别的地方引用过来的。

  • 相关阅读:
    acwing2-01背包问题
    背包问题(转载)
    考研易错点 二叉树的度和图的度
    考研易错点*s++
    考研复习易错点数组指针和指针数组
    Android Crash Learning
    Mysql5.7中的分组排序
    康师傅JVM:StringTable(十三)
    RocketMQ集群搭建
    RocketMq的单机安装
  • 原文地址:https://www.cnblogs.com/wangjingblogs/p/2277916.html
Copyright © 2011-2022 走看看