zoukankan      html  css  js  c++  java
  • 什么是扩展方法

    msdn是这样规定扩展方法的:“扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。”

    在类库中新建一个名为EString.cs类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace W.Common
    {
        public static class EString
        {
            /// <summary>
            /// 将字符串转换为Int
            /// </summary>
            /// <param name="t"></param>
            /// <returns>当转换失败时返回0</returns>
            public static int ToInt(this string t)
            {
                int id;
                int.TryParse(t, out id);//这里当转换失败时返回的id为0
                return id;
            }
        }
    }

    EString里有一个ToInt的静态方法,他接收一个自身参数this,类型为string,this string必须在方法参数的首位,它符合定义标准,因此ToInt是一个扩展方法。

    引用扩展方法的命名空间后即可直接调用

            /// <summary>
            /// 使用扩展方法
            /// </summary>
            private void IntExtTest()
            {
                string s = "2016";
                int i = s.ToInt(); 
            }

    博客原文:http://www.cnblogs.com/suger/archive/2012/05/13/2498248.html

  • 相关阅读:
    0109. Convert Sorted List to Binary Search Tree (M)
    03.Linux基础操作
    02windows基础操作
    API接口幂问题
    RocketMQ
    zookeeper
    JVM之参数调优
    JAVA多线程之线程池
    计算机网络常见问题
    英语词性之名词
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/6235478.html
Copyright © 2011-2022 走看看