• 泛型方法


    关于泛型方法,类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

  • 相关阅读:
    python-实现选择排序
    python-实现冒泡排序
    python-实现双端队列
    python-实现队列结构
    python-实现单向循环链表
    类型转换
    uint64_t类型输出为十六进制格式
    python文件的写入与读出
    linux系统中安装虚拟机
    IPv4和IPv6地址的存取
  • 原文地址:https://www.cnblogs.com/loveYN/p/4509716.html
Copyright © 2020-2023  润新知