当前位置:编程学习 > C#/ASP.NET >>

C# Timer的疑问

要完成一个功能,console每隔一秒输出一串字符,打算用Timer类,可是有个问题:
需要指定定时输出的函数,这个函数需要默认参数,但是我写的这个函数必须传入自己的参数,请问这要怎么做啊??

//
System.Timers.Timer t = new System.Timers.Timer(1000);
t.Elapsed += new System.Timers.ElapsedEventHandler(WriteToScreen);//使用默认参数的话这里是这样写,但是我的WriteToScreen函数想要有一个自己的参数,这样要怎么做??
 public void WriteToScreen(object source, System.Timers.ElapsedEventArgs e)//据说标准是这样,但是我还想传一个自己的参数啊

请帮忙吧 --------------------编程问答-------------------- using System;
using System.Timers ;
namespace ConsoleApplication9
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class Timer2
{
 
public static void Main()
{
// Create a new Timer with Interval set to 10 seconds.

System.Timers.Timer aTimer = new System.Timers.Timer(300);
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Only raise the event the first time Interval elapses.
aTimer.AutoReset = true;
aTimer.Enabled = true;
 
//Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');

}
 
// Specify what you want to happen when the event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e) 
{
Console.WriteLine("Hello World!");
}
}

} --------------------编程问答-------------------- 一个msdn上边的例子,我改了一下.. --------------------编程问答-------------------- to cxfcxf8():你没看明白我的疑问,我的疑问等价于在你给出的代码中OnTimedEvent(object source, ElapsedEventArgs e)这个函数如果我想加一个参数应该怎么做 --------------------编程问答-------------------- WriteToScreen只是1个事件,你想传什么参数,参数从哪里来 --------------------编程问答-------------------- 参数是我自己给出的,就是要在WriteToScreen中用到的,可不可以做到呢?? --------------------编程问答-------------------- 你可以在WriteToScreen调用1个外部全局变量,把这个全局变量当作你的参数 --------------------编程问答-------------------- 楼上的说得对,我一般也是这样做,不能通过函数传参数的时候,就做成全局变量,或者是一个类的成员字段 --------------------编程问答-------------------- 可以继承timer,加一个成员字段
class MyTimer:Timer
{
   public int Num{get;set;};//加一个字段
}

在用的时候把你要传的参数赋值
MyTimer timer ...
timer.Num=30;


在Elapsed 事件里可以拿回来用

MyTimer timer=(MyTimer )source;
Console.WriteLine(timer.Num);

补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,