zoukankan      html  css  js  c++  java
  • 扩展方法 extension method

    1.扩展方法可以扩展类型的功能,但无需修改类型本身,甚至可以使用扩展方法扩展不能修改的类型。

     为了扩展类型的功能,需要通过可以通过该类型的实例调用的方法,为此创建的方法称为扩展方法,他可以带任意数量的参数,返回类型。

    • 创建一个非泛型静态类
    • 使用扩展方法的语法,给创建的类添加扩展方法;
    • 通过扩展类型的一个实例调用扩展方法,与调用扩展类型的其他方法一样;

    要求如下:

    • 方法必须是静态的;
    • 方法必须包含一个参数,表示调用扩展方法的类型实例;
    • 实例参数必须是为方法定义的第一个参数
    • 除了this关键字之外,实例参数不能有其他的修饰符
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ExtensionLib
    {
        public static class WordProcessor
        {
            private const bool defaultval = false;
    
            public static List<string> GetWords(
                string sentence,
                bool capitalizwwords = false,
                bool reverseorder = defaultval,
                bool reverseWords = false
                )
            {
                List<string> words = new List<string>(sentence.Split(' '));
    
                return words;
            }
    
            public static string ToStringReversed(this object inputobject)
            {
                return inputobject.ToString();
            }
    
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                string sentence = "can be assigned the values true false or null.";
    
                Console.WriteLine(WordProcessor.GetWords(sentence).ToStringReversed());
                Console.WriteLine(sentence.ToStringReversed());
    
                Console.ReadLine();
            }
        }
    }
  • 相关阅读:
    (转)SQL Server索引进阶第四篇:页和区
    (转)SQL Server索引进阶第五篇:索引包含列
    CentOS虚拟化服务的配置(转)
    ubuntu 9.04安装xen(转)
    Linux的mount命令详解
    Linux环境下高级文件系统(转)
    安装和使用xenshell(转)
    (转)介绍ice 代理 不错的文章
    mapreduce介绍
    (转)Ubuntu Server Editon 时区设置
  • 原文地址:https://www.cnblogs.com/zzunstu/p/3405076.html
Copyright © 2011-2022 走看看