将参数传递给事件处理程序给出错误
Passing parameter to event handler giving errors
我有一个classAccount
。在其中我添加了一个名为 Activation
的操作并为其附加了一个事件处理程序。
这是代码:
public class Account
{
public event Action Activation;
public Account()
{
this.Activation += SendActivationEvent;
}
private void SendActivationEvent()
{
//do something here
}
}
这工作正常。现在我想给 SendActivationEvent
方法添加一个参数。我试过这样:
string sourceID = String.Empty;
this.Activation += SendActivationEvent(sourceID);
private void SendActivationEvent(string sourceID)
{
//do something here
}
它在 SendActivationEvent(sourceID)
处给出错误
Cannot implicitly convert type Void to System.Action
我该怎么做才能解决这个问题?
嗯,Action
不接受参数。请改用 Action<T>
(在您的情况下为 Action<String>
):
public class Account
{
// Note "String"
public event Action<String> Activation;
public Account()
{
// Assign method i.e. "SendActivationEvent",
// not method's result SendActivationEvent(sourceID)
this.Activation += SendActivationEvent;
}
private void SendActivationEvent(string sourceID)
{
//TODO: do something here
}
}
我有一个classAccount
。在其中我添加了一个名为 Activation
的操作并为其附加了一个事件处理程序。
这是代码:
public class Account
{
public event Action Activation;
public Account()
{
this.Activation += SendActivationEvent;
}
private void SendActivationEvent()
{
//do something here
}
}
这工作正常。现在我想给 SendActivationEvent
方法添加一个参数。我试过这样:
string sourceID = String.Empty;
this.Activation += SendActivationEvent(sourceID);
private void SendActivationEvent(string sourceID)
{
//do something here
}
它在 SendActivationEvent(sourceID)
处给出错误
Cannot implicitly convert type Void to System.Action
我该怎么做才能解决这个问题?
嗯,Action
不接受参数。请改用 Action<T>
(在您的情况下为 Action<String>
):
public class Account
{
// Note "String"
public event Action<String> Activation;
public Account()
{
// Assign method i.e. "SendActivationEvent",
// not method's result SendActivationEvent(sourceID)
this.Activation += SendActivationEvent;
}
private void SendActivationEvent(string sourceID)
{
//TODO: do something here
}
}