请问各位高手:委托是不是只能通过类名调用,不能通过实例调用?
如果可以通过实例调用,那么下例中为什么不能:
using System;
using System.Collections.Generic;
using System.Text;
namespace eventexample
{
class Usermintor
{
public delegate void DL(object sender, EventArgs e);
public event DL DEvent;
public void Run()
{
bool finished = false;
do
{
if (Console.ReadLine() == "h")
{
DEvent(this, new EventArgs());
}
}
while (!finished);
}
}
class Program
{
public Program(Usermintor m)
{
m.DEvent += new Usermintor.DL(this.ShowMessage);
}
public void ShowMessage(object sender,EventArgs e)
{
Console.WriteLine("Haha!!!");
}
static void Main(string[] args)
{
Usermintor us = new Usermintor();
new Program(us);
us.Run();
}
}
}
这里的m.dl不存在?
如果可以通过实例调用,那么下例中为什么不能:
using System;
using System.Collections.Generic;
using System.Text;
namespace eventexample
{
class Usermintor
{
public delegate void DL(object sender, EventArgs e);
public event DL DEvent;
public void Run()
{
bool finished = false;
do
{
if (Console.ReadLine() == "h")
{
DEvent(this, new EventArgs());
}
}
while (!finished);
}
}
class Program
{
public Program(Usermintor m)
{
m.DEvent += new Usermintor.DL(this.ShowMessage);
}
public void ShowMessage(object sender,EventArgs e)
{
Console.WriteLine("Haha!!!");
}
static void Main(string[] args)
{
Usermintor us = new Usermintor();
new Program(us);
us.Run();
}
}
}
这里的m.dl不存在?
using System.Collections.Generic;
using System.Text; namespace eventexample
{
//这2行移出来
public delegate void DL(object sender, EventArgs e);
public event DL DEvent; class Usermintor
{
public void Run()
{
bool finished = false;
do
{
if (Console.ReadLine() == "h")
{
DEvent(this, new EventArgs());
}
}
while (!finished);
}
} class Program
{
public Program(Usermintor m)
{
m.DEvent += new Usermintor.DL(this.ShowMessage);
} public void ShowMessage(object sender,EventArgs e)
{
Console.WriteLine("Haha!!!");
} static void Main(string[] args)
{
Usermintor us = new Usermintor();
new Program(us);
us.Run(); }
}
}
仅:
public delegate void DL(object sender, EventArgs e);
这行出去就可以
正确代码如下:using System;
using System.Collections.Generic;
using System.Text; namespace eventexample
{
//这1行移出来
public delegate void DL(object sender, EventArgs e);
class Usermintor
{
public event DL DEvent;
public void Run()
{
bool finished = false;
do
{
if (Console.ReadLine() == "h")
{
DEvent(this, new EventArgs());
}
}
while (!finished);
}
} class Program
{
public Program(Usermintor m)
{
m.DEvent += new Usermintor.DL(this.ShowMessage);
} public void ShowMessage(object sender,EventArgs e)
{
Console.WriteLine("Haha!!!");
} static void Main(string[] args)
{
Usermintor us = new Usermintor();
new Program(us);
us.Run(); }
}
}