• C#进阶 Methods下 Extension Methods


     1 c#的扩展方法

    从一个简单的例子开始

    namespace System { 
        
    public static class Class4 {
            
    public static string With(this string content, params string[] strs) {
                
    return string.Format(content, strs); 
            } 
        } 
    }
    .................主程序..............
    using System;
    namespace CLRLearn { 
        
    class Program { 
            
    static void Main(string[] args) { 
                Display(
    "hi {0}and{1} !".With(" ladys ""  gentleman !")); 
                Console.Read(); 
            }
            
    static void Display(object ob) { 
                Console.WriteLine(DateTime.Now.ToString() 
    + "      " + ob.ToString()); 
            }
        } 
    }

     值得注意的是 在Program 的.CS文件里 并没有 引用 扩展方法的命名空间,

    因为他的命名空间就是SYSTEM...这个又好又坏,对于多人来说,按理说命名空间不要取默认的。.23

    一些说明:

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

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

    2为集合做扩展方法

    public static void ShowItems<T>(this IEnumerable<T> collection) { 
    foreach (var item in collection) 
    Console.WriteLine(item); 
    }
    static void Main(string[] args) { 
             
    string statment=  "hi {0} and {1}".With("ladys""gentleman"); 
               Display(statment);
               statment.ShowItems
    <char>(); 
               Console.Read(); 
           }

    24

    3更多细节

    在你使用this参数扩展了方法之后,该程序集会在编译的时候会在对应静态类上加上类似以下的东西。以便于调用的时候方便找到。

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets. 
    Assembly)] 
    public sealed class ExtensionAttribute : Attribute { 
    }

    而他其实在运行时是需要引用System.Core.dll的。

     

    4扩展阅读

    扩展方法是我非常喜欢的一个特性,因为会让代码变漂亮很多。 代码的可读性是很重要的。

    不能不说的C#特性-扩展方法

    c#扩展方法奇思妙用

  • 相关阅读:
    你不能忽视的HTML代码2精编篇
    C#中析构函数和命名空间的妙用
    值类型和引用类型及其它
    这些年我收集的GDI+代码2
    C#中超级好用的字符串
    Javascript的压缩优化
    Spring和hibernate多个数据源的事务管理
    android中Handler,Looper,Message的开发答疑
    Spring引用Tomcat的 JTA事务
    js禁止用户刷新页面
  • 原文地址:https://www.cnblogs.com/facingwaller/p/1916679.html
Copyright © 2020-2023  润新知