我看了
如果您正在使用多播委托,您应该知道将被调用链接到同一委托的方法的顺序是正式未定义的.因此,您应该避免编写依赖于以任何特定顺序调用此类方法的代码.
但是当我尝试使用这段代码时
using System;
namespace Wrox.ProCSharp.Delegates
{
class Program
{
static void One()
{
Console.WriteLine("watch when i occur");
throw new Exception("Error in watching");
}
static void Two()
{
Console.WriteLine("count");
}
static void Three()
{
Console.WriteLine("great");
}
static void Main()
{
Action d1 = Two;
d1+=Two;
d1+=Two;
d1+=Two;
d1+=One;
d1+=Three;
d1+=Three;
d1+=Three;
Delegate[] delegates = d1.GetInvocationList();
foreach (Action d in delegates)
try
{
d1();
}
catch(Exception)
{
Console.WriteLine("Exception Caught");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
Run Code Online (Sandbox Code Playgroud)
显然,委托是按照我编写的指定顺序执行的,并且Three()在One()抛出异常的方法之前没有任何方法执行.
所以我缺少一些东西或者委托中的实际方法按指定的顺序执行,我从书中读到的东西意味着什么.
undefined - 行为被指定为任意的(就像你忘记妻子的生日后会发生什么......)所以取决于任意行为是有潜在危险的.
可能是5年后,微软发布了.NET 7,你的程序结果发生了变化.这是"未定义"的意思,今天没有多少测量值可以让您对下一个版本,甚至您的计算机和Fred的计算机之间感到舒适.所以观察它只是有趣的,但对可靠性没有用.依靠你观察到的东西在技术上是错误的.
有时,供应商会特别记录未定义的内容,以便在实施过程中保持灵活性.