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 に答える