• 扩展方法的使用


    示例如下:

    扩展方法
    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;//请自行完成
    }

  • 相关阅读:
    MySQL 获得当前日期时间 函数
    Jquery 将表单序列化为Json对象
    Eclipse远程调试(远程服务器端监听)
    使用Eclipse进行远程调控
    Java基础教程(3)--回顾HelloWorld
    Java基础教程(2)--Java开发环境
    Java基础教程(1)--概述
    4.9上机
    4.2上机
    第四周作业
  • 原文地址:https://www.cnblogs.com/BoYu045535/p/3682814.html
Copyright © 2020-2023  润新知