zoukankan      html  css  js  c++  java
  • 扩展方法的使用

    示例如下:

    扩展方法
    using System;
    using System.Collections.Generic; 

    using class1; //注意:引入扩展方法的空间

    namespace Con_1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str = "{0}女士 。".With("XuGang");
                Console.WriteLine("hello!" + str);

                //2调用集合的扩展方法
                str.ShowItems<char>();

            }
        }
    }

    namespace class1
    {
        //扩展方法必须在非泛型静态类中定义
        public static class MyMethods

        {
            //注意:第一个参数使用“this”获得当前对象
            public static string With(this string _context, params string[] _args)

            {
                return string.Format(_context,_args);
            }


            //2为集合做扩展方法
            public static void ShowItems<T>(this IEnumerable<T> _al)

            {
                foreach (var item in _al)
                {
                    Console.WriteLine(item);
                }
            }
        }
    }

    注意:

    1  C# 只支持扩展方法,不支持扩展属性、扩展事件等;

    2  方法名无限制,第一个参数必须带 this ;

    3  扩展方法的命名空间可以使用 namespace System ,但不推荐;

    4  定义扩展方法的类是静态类;

    5扩展方法中(如果文件中没有原来没有这个方法,这个方法是在后来加上去的话那么在调用的时候方法的样子就会有一个垂直的箭头,如果原来有的话这个 方法就会有一个扩展)

    如图

    public static string cc()
    {
    return "adfadsf";
    }
    public static string cc(this string name)
    {
    return name;
    }

    public static string GetChineseSpell(this string s)
    {
    return null;//请自行完成
    }

  • 相关阅读:
    亨元模式
    模板方法模式
    组合模式
    命令模式
    Android AIDL使用介绍(2)自定义数据类型的传递*
    Android主线程(ActivityThread)源代码分析
    一个简单的死锁代码*
    ABA问题的本质及其解决办法*
    Java 多线程Atomic 与CAS 原理剖析*
    Java并发编程:volatile关键字解析*
  • 原文地址:https://www.cnblogs.com/BoYu045535/p/3682814.html
Copyright © 2011-2022 走看看