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