これは、ページ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;
}
}
}
}