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);
  • 相关阅读:
    C#使用进度条,并用线程模拟真实数据 ProgressBar用法(转)
    装饰者模式(Decorator Pattern)C#版本的
    C# Stream篇(七) -- NetworkStream
    C# Stream篇(六) -- BufferedStream
    C# Stream篇(五) -- MemoryStream
    C# Stream篇(四) -- FileStream
    C# Stream篇(三) -- TextWriter 和 StreamWriter
    C# Stream篇(二) -- TextReader 和StreamReader
    C# Stream篇(—) -- Stream基类
    代理模式(Proxy Pattern)C#版本的
  • 原文地址:https://www.cnblogs.com/howtrace/p/11213230.html
Copyright © 2011-2022 走看看