17,740
社区成员
发帖
与我相关
我的任务
分享
public class 机器
{
virtual public object Run()
{
return "运行";
}
virtual public void combine(机器 x)
{
throw new NotImplementedException();
}
public virtual IEnumerable<机器> GetInvocationList()
{
return new 机器[] { this };
}
}
public class 多机器 : 机器
{
private List<机器> lst = new List<机器>();
public override void combine(机器 x)
{
lst.Add(x);
}
public override IEnumerable<机器> GetInvocationList()
{
return lst;
}
public override object Run()
{
object result = null;
foreach (var x in lst)
result = x.Run();
return result;
}
}
以现在的OOP设计原则来看,我们应该坚决反对这种程序。不是说能执行就行了,我们当让还要求逻辑上更自然,能够更长久地使用(当然任何真理都有被推翻的那一天)。
不自然地继承关系,与一般人的理解有冲突的东西,当然应该尽早重构。就算微软不改,我们也不应该学微软。delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y) {
Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
Console.WriteLine("You r in Method 2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}
解析:
上面的示例程序分别定义了名为method1 和 method2的两个接受整型参数、返回类型为void的方法。
多播委托:
(1)多播委托包含一个以上方法的引用。
(2)多播委托包含的方法必须返回void,否则会抛出run-time exception。