zoukankan      html  css  js  c++  java
  • Net C# 扩展方法

    Net C# 扩展方法

    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

    好处:
    不修改原有类型的实现

    调用:
    调用以成员函数方式调用,静态实现

    范例:
    using System.Linq;
    using System.Text;
    using System;

    namespace CustomExtensions
    {
        //Extension methods must be defined in a static class
        public static class StringExtension
        {
            // This is the extension method.
            // The first parameter takes the "this" modifier
            // and specifies the type for which the method is defined.
            public static int WordCount(this String str)
            {
                return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
            }
        }
    }
    namespace Extension_Methods_Simple
    {
        //Import the extension method namespace.
        using CustomExtensions;
        class Program
        {
            static void Main(string[] args)
            {
                string s = "The quick brown fox jumped over the lazy dog.";
                //  Call the method as if it were an
                //  instance method on the type. Note that the first
                //  parameter is not specified by the calling code.
                int i = s.WordCount();
                System.Console.WriteLine("Word count of s is {0}", i);
            }
        }
    }

    上述代码实现的字统计

    你也可以采用继承的方式来实现

    public class StringExtension : String
    {
        public int WordCount()
        {
        ......
        }


    调用上,这是两个不同的类别处理。


    =======================================================

    看到这里,如果学习Objective-C,就知道Category这个东西,就是用于扩展方法。

    看来C#这个语言,从多类语言中吸取各自的优点,混装了自己~

    至于Objective-C的Category,这里不做介绍和比对

    =======================================================




  • 相关阅读:
    记一次跳转
    html2canvas在生成图片过程中遇到的坑vue
    数组对象push新的元素,导致其他新复制的数据也发生改变,不是一一对应改变(深拷贝和浅拷贝)
    js生成的新结构点击事件不生效
    箭头函数和普通函数的区别
    vue (vue-cli主要写构建工具的使用)
    favicon.ico可能会遇到的的坑
    video不能在个别浏览器不能播放
    a标签的拨打电话、发邮件、QQ发消息,另外控件分享转发
    git使用的简单命令
  • 原文地址:https://www.cnblogs.com/GoGoagg/p/2127697.html
Copyright © 2011-2022 走看看