必须在非泛型静态类中定义扩展方法 - Extend System.Delegate?

时间:2012-10-31 21:54:50

标签: .net c#-4.0 c#-3.0 extension-methods

这是参考页面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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分: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()