100分,请高手帮我说说以下代码中说的“事件与委托”的怪现象。谢谢了,在线,立即给。
代码如下:
using System;
public delegate string daili(string a,int b);
namespace Test{
public event daili shijian;
class test
{
Result r = new Result();
shijian+=new daili(r.test_shijian);//A
shijian+=new daili(r.printt);//B
}
public void Invoke()
{
if(shijian!=null)
{
Console.Write(shijian( "试试! ",12345));
}
}
Class Result
{
public string test_shijian(string k,int j)
{
return k+j.ToString();
}
public string printt(string k,int j)
{
return "这里为了与上面那个方法区别开,所以用这些字 ";
}
}
///以下面是应用了
public class Client{
public static void Main(string[] args)
{
test i=new test();
i.Invoke();//触发那个事件。
}
}
我的问题是,调试时每次都只显示一个结果,也就是只显示A或B(他俩哪个在后显示哪一个,这是什么??难道只执行最后的一个??请高手指点)。我在线等您,谢谢,看贴的各位。
------解决方案--------------------using System;
namespace ConsoleApplication1
{
public delegate void MyDelegate();
public interface I
{
event MyDelegate MyEvent;
void FireAway();
}
public class MyClass:I
{
public event MyDelegate MyEvent;
public void FireAway()
{
if(MyEvent!=null)
MyEvent();
else
Console.WriteLine( "MyEvent failed! ");
}
}
public class MainClass
{
static private void f()
{
Console.WriteLine( "F is called ..................... ");
return;
}
static private void fl()
{
Console.WriteLine( "FL is called ..................... ");
Console.ReadLine();
return;
}
static public void Main()
{
/*
* 可以使用接口定义!
I iMy;
iMy=new MyClass();
iMy.FireAway();
iMy.MyEvent +=new MyDelegate(f);
iMy.MyEvent +=new MyDelegate(fl);
iMy.FireAway();
*/
MyClass i=new MyClass();
i.FireAway();
i.MyEvent +=new MyDelegate(f);
i.MyEvent +=new MyDelegate(fl);
i.FireAway();
}
}
}
------解决方案--------------------using System;
namespace Test
{
public delegate string daili(string a, int b);
public class test
{
public event daili shijian;
public test()
{
Result r = new Result();
shijian += new daili(r.test_shijian);//A
shijian += new daili(r.printt);//B
}
public void Invoke()
{
if (shijian != null)
{
shijian( "试试! ", 12345);
//Console.WriteLine(shijian( "试试! ", 12345));
}
}
}
public class Result
{
public string test_shijian(string k, int j)
{
Console.WriteLine(k + j.ToString());
return k + j.ToString();
}
public string printt(string k, int j)
{
Console.WriteLine( "这里为了与上面那个方法区别开,所以用这些字 ");
return "这里为了与上面那个方法区别开,所以用这些字 ";