扩展方法问题

Al.*_*Al. 0 .net c# c#-4.0

码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace LambdaExtensionEx
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] myStrngs = new string[] { "Super","Simple","Okay"};
            IEnumerable<string> criteraStrngs = myStrngs.WhereSearch<string>(delegate(string s)
            {
                return s.StartsWith("s");
            });

            string s1 = "dotnet";
            int count = s1.GetCount();

            Console.ReadLine();
        }
    }

    public static class MyExtension
    {
        public delegate bool Criteria<T>(T Value);

        public static IEnumerable<T> WhereSearch<T>(this IEnumerable<T> values, Criteria<T> critera)
        {
            foreach (T value in values)
                if (critera(value))
                    yield return value;
        }

        public static int GetCount(this string value)
        {
            return value.Count();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以调用GetCount扩展方法,我得到'count'的结果.但WhereSearch在任何时候都没有被调用而没有得到结果.我做错了什么?

Dar*_*rov 5

WhereSearch如果要执行该函数,则需要开始枚举函数返回的结果.原因是因为这个功能yield returnsIEnumerable<T>.C#编译器所做的是构建一个状态机,并且在调用代码开始枚举结果之前不立即执行该函数.

例如:

// The function is not executed at this stage because this function uses 
// yield return to build an IEnumerable<T>
IEnumerable<string> criteraStrngs = myStrngs.WhereSearch<string>(delegate(string s)
{
    return s.StartsWith("s");
});
// Here we start enumerating over the result => the code will start executing
// the function.
foreach (var item in criteraStrngs)
{
    Console.WriteLine(item);
}
Run Code Online (Sandbox Code Playgroud)

另一个例子是调用一些LINQ扩展方法,例如.ToList()实际枚举和调用函数的结果:

IEnumerable<string> criteraStrngs = myStrngs.WhereSearch<string>(delegate(string s)
{
    return s.StartsWith("s");
})
.ToList();
Run Code Online (Sandbox Code Playgroud)

有关延迟加载在这种情况下如何工作的更多详细信息,您可以查看following post.