SKL*_*TFZ 1 c# asp.net eventhandler
我想问之间的不同EventHandler和EventHandler<T>.
以前我EventHandler用一个自定义的EventArgs 实现了一个可以从用户控件传递到父页面的事件.
我认为我需要申请EventHandler< T >,但它可以通过使用来实现EventHandler.(事实上,当我尝试应用时出现奇怪的错误EventHandler<T>,程序运行但是IDE中显示的错误是我无法解决的[ C#Custom EventHandler ])
因此,我想知道我需要申请什么情况EventHandler < T >?
public event EventHandler AppendProcess;
public event EventHandler<MyEventArg> AppendProcess;
Run Code Online (Sandbox Code Playgroud)
---更新---这是我在用户控件中调用事件的方式(正如我所说,我可以通过这样做将对象传递给父页面(尽管我不知道这样做是否正确)
if (AppendProcess == null) { }
else
AppendProcess(this, new Common.WinLose_ProgressStage(Common.WinLose_SP_Parameter.upper, displayLevel + 1,
(int)Common.WinLose_Level.lvChild4, thename, refundratio,
selfproportion, -1, -1, loadlevel, isPlayer, betsource, gamecategory, false));
Run Code Online (Sandbox Code Playgroud)
EventHandler<T>它只是一个泛型EventHandler类型,它避免了为每种EventArgs想要使用的类型声明一个新的委托类型.
Control.KeyPress例如,考虑一下.它被声明为类型的事件KeyPressEventHandler.该代表刚刚宣布为:
public delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e)
Run Code Online (Sandbox Code Playgroud)
如果EventHandler<T>(和泛型)在创建时已存在,则事件可能已被声明为,EventHandler<KeyPressEventArgs>而是保存委托声明.有许多代表就像EventHandler,只有第二个参数的类型不同 - EventHandler<T>避免冗余.
不,如果你不具备自己的自定义EventArgs子类,没有理由使用EventHandler<T>...但如果你这样做,这是更好的使用它,因此该方法处理事件接收自定义EventArgs的强类型的方法子类.
另外,调用事件处理程序的方式不是线程安全的.另一个线程可以在您的无效检查后取消订阅最终事件处理程序.如果您使用的是C#5,则应将其编写为:
var handler = AppendProcess;
if (handler != null)
{
handler(this, new Common.WinLose_ProgressStage(...));
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C#6或更高版本,则可以使用null条件运算符:
// If AppendProcess is null, the arguments won't even be evaluated
AppendProcess?.Invoke(this, new Common.WinLose_ProgressStage(...));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3920 次 |
| 最近记录: |