我承认,我正在做家庭作业,但我一直坚持这个问题(A部分)。如何通过通知方法作为铁路信号的参考?我是否只能找出抽象构造函数中调用了哪个类,然后在notify方法中打印类名称?例如:铁路用户private string className;public RailwayUser(){ Type type = this.GetType(); className = type.Name;}public void PrintClassName(){ Console.Writeline(className);}铁路信号类public void Notify(){ foreach(RailwayUser u in _watches) { u.PrintClassName(); u.Notice(State) }} 最佳答案 这种代码/设计有缺陷,因为它执行的是RailwayUser,将对象引用注册到_watchers类中的RailWaySignal列表中,当被调用,这不是Notice或Notify的工作方式。实际上,public Event Signaling是危险的,因为任何用户都可以清除它,尽管可以使用属性访问来进行管理。有问题的代码public void Notify(){ foreach(RailwayUser u in _watches) { u.PrintClassName(); u.Notice(State) }}以下是使用事件和委托的实际代码:正确版本在线代码段-https://www.jdoodle.com/embed/v0/uEcvoid Main(){ List<RailwayUser> railwayUsers = new List<RailwayUser>(); railwayUsers.Add(new RailwayUser()); railwayUsers.Add(new RailwayUser()); RailwayUser.TestNotification();}public enum Colour{ Red, Green, NoSignal}public class RailwaySignal{ public string Name {get; set;} public RailwaySignal(string railwaySignalName) { Name = railwaySignalName; } // Delegate for handling event public delegate void RailwaySignalEventHandler(object source, Colour e); // Delagate object for handling event private RailwaySignalEventHandler _railwaySignalEvent; // Event Accessor public event RailwaySignalEventHandler RailwaySignalEvent { add { lock (this) { _railwaySignalEvent += value; } } remove { lock (this) { _railwaySignalEvent -= value; } } } // Invoke Event for subscribed clients private void Notify() { if (_railwaySignalEvent != null) _railwaySignalEvent.Invoke(this, Colour.Green); } // Test the Event Invocation public void TestEvent() { Notify(); }}public class RailwayUser{ private static RailwaySignal railwaySignal { get; set;} = new RailwaySignal("Signal1"); public RailwayUser() { railwaySignal.RailwaySignalEvent += this.Notice; } public static void TestNotification() { railwaySignal.TestEvent(); } public void Notice(object sender, Colour color) { Console.WriteLine($"Notice Called, Colour is :: {color}, Sender is :: {((RailwaySignal)sender).Name}"); }}结果Notice Called, Colour is :: Green, Sender is :: Signal1Notice Called, Colour is :: Green, Sender is :: Signal1重要细节事件的签名是Function Pointer,它有助于将相关信息传递给被调用的_watchers。我们现在知道,RailwaySignal会触发向RailwayUser及其颜色值的通知事件/委托具有与被调用方法相同的签名(这是委托/函数指针的工作基础)为了简化起见,(object source, Colour e)是一个非抽象类事件是使用RailwayUser内部的RailwayUser方法执行的,我们只是出于演示目的使用Notify()内部的RailwaySignal人工调用它,但理想情况下,它应在内部触发并应传递当前状态,例如Color像TestNotification(),RailwayUser之类的预定义委托通常用于类似的通知机制,尽管在内部声明为Func的显式Action是明确定义的模式,但它们内部使用类似的机制工作,尤其是对于Ui控件.Net框架公开的标准事件具有签名event,其中delegate可以将所有信息从事件执行程序(RailwaySignal)包装到事件接收者(RailwayUser) 08-27 14:16