zoukankan      html  css  js  c++  java
  • C# 中扩展方法应用

    扩展方法是C# 3.0 中新增特性,可在不修改源类代码情况,通过ADD File 模式对源代码功能扩展。

    扩展方法要求如下:

    a.扩展方法需包含在 static 修饰类中.

    b.扩展实现需是静态形式。

    c.扩展方法第一个参数 前缀为 this , 表示需要扩展类对象,从第二个参数开始,为扩展方法参数列表。

    1.基础类型扩展示例

    如下扩展对字符类型增加换行符:

    public static  class StringExt
        {
            public static string AddNewLine(this string str) {
                return str + Environment.NewLine;
            }
        }

     如下扩展方法将字典类型Value 值拼接返回:

     public static  class DictionaryToEXT
        {
            public static string DictionaryToString<T1, T2>(this Dictionary<T1, T2>  dic ) {
                StringBuilder strBui = new StringBuilder();
                foreach (KeyValuePair<T1, T2> k in dic) {
                    strBui.AppendLine(k.Value.ToString());
                }
    
                return strBui.ToString();
            }
        }

     2.泛型扩展方法

    泛型扩展,对任意对象增加 ExtToString  方法.

     public static string ExtToString<T>(this T t){
                return t.ToString();
            }

     下面是比较复杂泛型扩展方法推断,注意,扩展方法之后的泛型参数不能做为扩展方法签名中一部份:

     public static class PipelineStepExtensions
        {
            public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPiPelineStep<INPUT, OUTPUT> step) 
            {
                return step.Process(input);
            }
    
            public static object Step<INPUT>(this INPUT input, IPiPelineStep<INPUT, object> step)
            {
                return step.Process(input);
            }
    
        }

    testMethod.Step(pppp) 实际调用: public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPiPelineStep<INPUT, OUTPUT> step) 

    testMethod.Step(ppppObject); 实际调用:public static object Step<INPUT>(this INPUT input, IPiPelineStep<INPUT, object> step)

     如下调整,也能编译通过,表明泛型扩展方法签名与泛型参数个数没有关系 , testMethod 只有一个泛型参数,而 Step 扩展有两个泛型参数 :

     public static class PipelineStepExtensions
        {
            public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPiPelineStep<INPUT, OUTPUT> step) 
            {
                return step.Process(input);
            }
    
            //public static object Step<INPUT>(this INPUT input, IPiPelineStep<INPUT, object> step)
            //{
            //    return step.Process(input);
            //}
    
        }
      TestGuanDao<int> testMethod = new TestGuanDao<int>();
       
      IPipelineStepDic<TestGuanDao<int> , string> pppp = new IPipelineStepDic<TestGuanDao<int>, string>();
    
      testMethod.Step(pppp);
  • 相关阅读:
    剑指 Offer 41. 数据流中的中位数
    剑指 Offer 19. 正则表达式匹配
    leetcode 75 颜色分类
    Deepin 添加 open as root
    window 下 无损进行其他文件系统(ext4) 到 ntfs 文件系统的转化
    Windows Teminal Preview Settings
    CentOS 7 容器内替换 apt-get 源为阿里源
    Ubuntu 20.04 安装 Consul
    elementary os 15 添加Open folder as root
    elementary os 15 gitbook install
  • 原文地址:https://www.cnblogs.com/howtrace/p/11213230.html
Copyright © 2011-2022 走看看