zoukankan      html  css  js  c++  java
  • 泛型方法

    关于泛型方法,类Enumerable内含相当多的泛型方法的使用.Enumerable类定义的注释如下:

    // 摘要:
    //     提供一组用于查询实现 System.Collections.Generic.IEnumerable<T> 的对象的 static(在 Visual
    //     Basic 中为 Shared)方法

    由此注释,我们可以看到,凡是实现了System.Collections.Generic.IEnumerable<TSource>的对象都可以使用此类中定义的方法.

    挑其中一个方法来看.

    public static IEnumerable<TResult> Select<TSource, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TResult> selector
    )

    返回值IEnumerable<TResult>:

    返回值类型:

    • System.Collections.Generic.IEnumerable<TResult>

    返回值:

    • 返回一个序列,此序列中的元素为对source中的每个元素调用selector方法后返回的元素结果.

    类型参数<TSource, TResult>:

    TSource:

    • source中元素的类型

    TResult:

    • selector返回的值的类型

    参数:

    source:

    • System.Collections.Generic.IEnumerable<TSource>,一个值序列,要对该序列调用selector转换函数

    selector:

    • System.Func<TSource, TResult>,应用于每个元素上的转换函数.

    例子:

    protected void Page_Load(object sender, EventArgs e)
    {
        string[] strs = new string[]
        {
            "abcd",
            "abcee",
            "bcde",
            "123s"
        };
    
        //四种调用方法都可以
        //IEnumerable<string> result = strs.Select<string, string>(x => x.StartsWith("ab") ? x : string.Empty);
        //IEnumerable<string> result = strs.Select(x => x.StartsWith("ab") ? x : string.Empty);
        //IEnumerable<string> result = Enumerable.Select<string, string>(strs, x => x.StartsWith("ab") ? x : string.Empty);
        IEnumerable<string> result = Enumerable.Select(strs, x => x.StartsWith("ab") ? x : string.Empty);
        foreach (var r in result)
        {
            Response.Write(r.ToString()+"<br/>");
        }
    }

    效果:

    abcd
    abcee

  • 相关阅读:
    1105 Spiral Matrix (25分)(蛇形填数)
    1104 Sum of Number Segments (20分)(long double)
    1026 Table Tennis (30分)(模拟)
    1091 Acute Stroke (30分)(bfs,连通块个数统计)
    1095 Cars on Campus (30分)(排序)
    1098 Insertion or Heap Sort (25分)(堆排序和插入排序)
    堆以及堆排序详解
    1089 Insert or Merge (25分)
    1088 Rational Arithmetic (20分)(模拟)
    1086 Tree Traversals Again (25分)(树的重构与遍历)
  • 原文地址:https://www.cnblogs.com/loveYN/p/4509716.html
Copyright © 2011-2022 走看看