嗨,如果比较,我已经筋疲力尽了。和切换案例方法。我已阅读以下问题:
这个用法很好。看看维维克的回应。
我的用法如下,但我不能这样。
namespace DelegateKavrami
{
class Program
{
static void Main(string[] args)
{
new MyTest().Run();
Console.Read();
}
}
public class MyTest
{
public void Run()
{
MyMessageProcessor myProcessor = new MyMessageProcessor();
myProcessor.Register(0, Sms);
myProcessor.Register(1, Mms);
myProcessor.ProcessMessage(1, Message.Sms);
}
public void Sms(Message message)
{
Console.WriteLine("Sms olarak gönderilen mesaj");
}
void Mms(Message message)
{
Console.WriteLine("Mms olarak gönderilen mesaj:");
}
}
public class MyMessageProcessor
{
public delegate void ProcessMessageDelegate(Message message);
Dictionary methods;
public void Register(int messageType,
ProcessMessageDelegate processMessage)
{
methods[messageType] = processMessage;
}
public void ProcessMessage(int messageType, Message message)
{
if (methods.ContainsKey(messageType))
{
methods[messageType](message);
}
}
}
public enum Message
{
Sms,Mms
}
}
但我的梦想
myProcessor.ProcessMessage(1)
我怎么能用这个?上述代码运行后出错:对象引用未设置为对象的实例。ON 方法[messageType] = processMessage;