小弟初学C#,有一程序不解!望达人解答!

gddong 2008-02-29 08:34:38
程序:
1 using System;
2 class UserInputMonitor
3 {
4 public delegate void UserRequest(object sender,EventArgs e);
5 public event UserRequest OnUserRequest;
6 public void Run()
7 {
8 if (Console.ReadLine()=="h")
9 OnUserRequest(this,new EventArgs());
10 }
11 }
12 public class Client
13 {
14 public static void Main()
15 {
16 UserInputMonitor monitor=new UserInputMonitor();
17 new Client(monitor);
18 monitor.Run();
19 }
20 private void ShowMessage(object sender,EventArgs e)
21 {
22 Console.WriteLine("HaHa!!");
23 }
24 Client(UserInputMonitor m)
25 {
26 m.OnUserRequest+=new UserInputMonitor.UserRequest(this.ShowMessage);
27 }
28 }

这是一个事件处理程序,用来监听键盘的输入.
我想把24,25,26,27行去掉,改动一下第17行,可以怎么改?
...全文
149 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
syeerzy 2008-03-01
  • 打赏
  • 举报
回复
改这个很容易,但是我的问题是“为什么要改”????

非要把一个写得还算不错的程序给改坏么?
fox_sky 2008-03-01
  • 打赏
  • 举报
回复
很容易,把17行改成:
monitor.OnUserRequest+=new UserInputMonitor.UserRequest(new Program().ShowMessage);
gxj760998 2008-03-01
  • 打赏
  • 举报
回复
this意味着当前实例,静态是没有的实例区别的,
LZ要去看看基本的东西啦
gddong 2008-03-01
  • 打赏
  • 举报
回复
改这个很容易,但是我的问题是“为什么要改”????

非要把一个写得还算不错的程序给改坏么?

====================================================================

也许你是对的,不过我觉得改了之后程序更简洁,更具有可读性!
gddong 2008-02-29
  • 打赏
  • 举报
回复
楼上两位:
你们的方法我以前也这样改过,可是编译无法通过.
第17行:关键字“this”在静态属性、静态方法或静态字段初始值设定项中无效
不过还是谢谢你们!
FatherOfCodingMan 2008-02-29
  • 打赏
  • 举报
回复
1 using System;
2 class UserInputMonitor
3 {
4 public delegate void UserRequest(object sender,EventArgs e);
5 public event UserRequest OnUserRequest;
6 public void Run()
7 {
8 if (Console.ReadLine()=="h")
9 OnUserRequest(this,new EventArgs());
10 }
11 }
12 public class Client
13 {
14 public static void Main()
15 {
16 UserInputMonitor monitor=new UserInputMonitor();
17 monitor.OnUserRequest+=
new UserInputMonitor.UserRequest(this.ShowMessage);
18 monitor.Run();
19 }
20 private void ShowMessage(object sender,EventArgs e)
21 {
22 Console.WriteLine("HaHa!!");
23 }
28 }
cww2010 2008-02-29
  • 打赏
  • 举报
回复
程序:
1 using System;
2 class UserInputMonitor
3 {
4 public delegate void UserRequest();
5 public event UserRequest OnUserRequest;
6 public void Run()
7 {
8 if (Console.ReadLine()=="h")
9 OnUserRequest();
10 }
11 }
12 public class Client
13 {
14 public static void Main()
15 {
16 UserInputMonitor monitor=new UserInputMonitor();
17 monitor.OnUserRequest+=new UserInputMonitor.UserRequest(this.ShowMessage); 18 monitor.Run();
19 }
20 private void ShowMessage(object sender,EventArgs e)
21 {
22 Console.WriteLine("HaHa!!");
23 }
24
28 }



4 public delegate void UserRequest(); 参数如果没用的话就不用加了.

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧