0

这是参考页面http://msdn.microsoft.com/en-us/library/orm-9780596516109-03-09.aspx中的代码示例

C# 编译器期望该EveryOther()方法在它自己的静态类中定义。

我是否需要System.Delegate使用新方法进行扩展EveryOther()

namespace DelegateTest
{    
    public class TestInvokeIntReturn
    {
        public static int Method1()
        {
            Console.WriteLine("Invoked Method1");
            return 1;
        }

        public static int Method2()
        {
            Console.WriteLine("Invoked Method2");
            return 2;
        }

        public static int Method3()
        {
            //throw (new Exception("Method1"));
            //throw (new SecurityException("Method3"));
            Console.WriteLine("Invoked Method3");
            return 3;
        }
    }

    class Program
    {       
        static void Main(string[] args)
        {
            Func<int> myDelegateInstance1 = TestInvokeIntReturn.Method1;
            Func<int> myDelegateInstance2 = TestInvokeIntReturn.Method2;
            Func<int> myDelegateInstance3 = TestInvokeIntReturn.Method3;

            Func<int> allInstances = //myDelegateInstance1;
                    myDelegateInstance1 +
                    myDelegateInstance2 +
                    myDelegateInstance3;

            Delegate[] delegateList = allInstances.GetInvocationList();
            Console.WriteLine("Invoke every other delegate");
            foreach (Func<int> instance in delegateList.EveryOther())
            {
                // invoke the delegate
                int retVal = instance();
                Console.WriteLine("Delegate returned " + retVal);
            }
        }

        static IEnumerable<T> EveryOther<T>(this IEnumerable<T> enumerable)
        {
            bool retNext = true;
            foreach (T t in enumerable)
            {
                if (retNext) yield return t;
                retNext = !retNext;
            }
        }
    }
}
4

1 回答 1

0

EveryOther用作扩展方法,您必须将其放在静态类中:

public static class MyExtensions
{
    public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> enumerable)
    {
        bool retNext = true;
        foreach (T t in enumerable)
        {
            if (retNext) yield return t;
            retNext = !retNext;
        }
    }
}

如果您不想将其用作扩展方法,则可以将签名更改EveryOther

static IEnumerable<T> EveryOther<T>(IEnumerable<T> enumerable)

然后只需调用EveryOther(delegateList)而不是delegateList.EveryOther().

于 2012-10-31T21:59:57.763 回答