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

      扩展方法,它允许定义一个静态方法,并用实例方法的语法来调用它。定义的时候,第一个参数是和当前用于调用方法的那个表达式(下例中的sb(StringBuilder))的类型匹配的一个类型,且须在参数前添加 this 关键字。先看个例子:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ExtensionMethod
    {
        // 在此类中定义扩展方法
        public static class StringBuilderExtensions
        {
            public static Int32 IndexOf(this StringBuilder sb, Char Value)
            {
                for (Int32 index = 0; index < sb.Length; index++)
                {
                    if (sb[index] == Value)
                        return index;
                }
    
                return -1;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                StringBuilder sb = new StringBuilder("Hachun");
                
                // sb对象直接调用扩展方法 IndexOf
                Int32 pos = sb.IndexOf('c');
                Console.WriteLine(pos);
                Console.ReadKey();
            }
        }
    }

      扩展方法的一些原则:

    1.c#只支持扩展方法,不支持扩展属性,扩展事件等,但可以为接口类型定义扩展方法,任何实现该接口的类,都可以调用此扩展方法;

    2.扩展方法必须在非泛型的静态类中声明,类名没有限制,可以随意叫。当然,扩展方法至少要有一个参数,且须用 this 标记;

    3.c#编译器查找静态类中定义的扩展方法时,要求这些静态类本身必须具有文件作用域(类要有整个文件的作用域,而不能嵌套到一个类中,只具有该类的作用域)。换言之,如果静态类嵌套在另一个类中,c#编译器会报错;

    4.用一个扩展方法扩展一个类时,相应的派生类也会被扩展,所以,慎用;

  • 相关阅读:
    linux:shell:tree
    html5,css3
    asp.net web forms page life cycle
    Unobtrusive Javascript
    Multitier architecture
    C#接口的显示实现和隐式实现
    Modernizr
    android w700
    debian e42 wifi
    mstest run dll
  • 原文地址:https://www.cnblogs.com/hachun/p/4549078.html
Copyright © 2011-2022 走看看