我想构建MyTimer类但不能将方法名称作为参数。它说“无法在静态上下文中访问非静态方法'TimerCallBack'。我知道如果方法是静态的,但是我想将这个类用于静态和非静态的timercallback方法。我可以直接给出方法名称测试类中的计时器对象,但是当我尝试提供给MyTimer并在计时器对象中使用此参数时,它不起作用。我该如何解决这个问题?
class MyTimer
{
private System.Threading.Timer _timer;
private int _period;
private int _dueTime;
public MyTimer(TimerCallback timerCallBack, int period = System.Threading.Timeout.Infinite,
int dueTime = System.Threading.Timeout.Infinite, object _state = null)
{
this._period = period;
this._dueTime = dueTime;
_timer = new System.Threading.Timer(timerCallBack, _state, dueTime, period);
}
public void Start(int period = 0)
{
if (_timer != null)
{
if (period != 0)
{
_period = period;
}
_timer.Change(_dueTime, _period);
}
}
public void Stop()
{
_timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
}
public void Change(int dueTime, int period)
{
if (dueTime!= System.Threading.Timeout.Infinite)
{
_dueTime = dueTime;
}
if (period != System.Threading.Timeout.Infinite)
{
_period = period;
}
_timer.Change(_dueTime, _period);
}
public void Period(int period)
{
if (period >= 0)
{
_period = period;
}
}
public void DueTime(int dueTime)
{
if (dueTime >= 0)
{
_dueTime = dueTime;
}
}
public void Dispose()
{
_timer = null;
}
}
class test
{
private MyTimer _timer = new MyTimer(TimerCallBack, 1, 0, null);
void TimerCallBack(object state)
{
//Do something
}
}
答案 0 :(得分:1)
您需要做的就是将_timer
对象的初始化移动到构造函数中,如下所示:
class test
{
private MyTimer _timer; // Removed field initializer.
// Added constructor.
internal test()
{
// Moved initialization of _timer into constructor.
_timer = new MyTimer(TimerCallBack, 1, 0, null);
}
void TimerCallBack(object state)
{
//Do something
}
}
错误表明字段初始值设定项不能使用非静态成员(在本例中为TimerCallBack
方法)。字段初始值设定项在构造函数之前运行,因此在构造实例之前,字段初始值设定项无法使用实例成员(即TimerCallBack
方法)。
答案 1 :(得分:0)
根本就不要使用TimerCallback!
您可以像这样定义一个委托:
public class MyClass
{
public delegate void callableMethod();
callableMethod outsideMethod;
public MyClass(callableMethod usersMethod)
{
outsideMethod = usersMethod;
}
}
然后你可以在MyClass的某处调用它:
outsideMethod();