zoukankan      html  css  js  c++  java
  • [C#] Extension Method 扩展方法

    当我们引用第三方的DLL、或者Visual Studio自己的库的时候,或许会发现这样的一个情况,如果这个类型有一个XX的方法就好了。这时候我们可以用到扩展方法,是我们的代码更加灵活和高效。

    这里我举例一下,比如在控制台程序(Console Application)我们想打印一个List<string>内所有的成员通常会怎么写么?

    最通常的方法:

    List<string> StringList = new List<string>();
    foreach (var item in StringList)
    {
        Console.WriteLine(item);
    }

    这个劣势显而易见我们每次要打印时候都要不断的重复这一段代码,但是现在有一个捷径,我们来尝试“扩展方法”(Extension Method)。首先我们要来扩展List<string>,给它一个新的方法PrintMember

    namespace PegasusZero.Extensions
    {
        public static class ListExtension
        {
            public static void PrintMember(this List<string> listInstance) {
                foreach (var item in listInstance)
                {
                    Console.WriteLine(item);
                }
            }
        }
    }

    然后我们只要在引用之前引用这个namespace,就可以直接调用这个扩展的方法了。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using PegasusZero.Extensions;
    
    namespace PegasusZero.Demo.ExtensionMethod
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<string> StringList = new List<string>();
                StringList.Add("Copyright (c)2013 PegasusZero");
                StringList.Add("Item 1");
                StringList.Add("Item 2");
                StringList.Add("Item 3");
                StringList.Add("Item 4");
                StringList.Add("Item 5");
    
                StringList.PrintMember();
            }
        }
    }

    这面并没有使用Console.WriteLine(),但是我们可以看到Magic的事情发生了~ TADA!

    ExtensionMethod

    下面是一个院子里大神的扩展集合贴,用大神自己的话他“走火入魔“了。(传送门<-狂戳这里去学习吧)

    MSDN Reference:

    http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx (英文)

    http://msdn.microsoft.com/zh-cn/library/vstudio/bb383977.aspx (中文)

  • 相关阅读:
    How to extract msu/msp/msi/exe files from the command line
    Windbg and resources leaks in .NET applications 资源汇总
    [c# 20问] 3.String和string的区别
    [c# 20问] 2.如何转换XML文件
    [c# 20问] 1. 何时使用class与struct
    安装配置BITS上传服务
    The J-Link hardware debugging Eclipse plug-in
    swift material
    SCLButton
    ChatCell
  • 原文地址:https://www.cnblogs.com/PegasusZero/p/3400517.html
Copyright © 2011-2022 走看看