我理解事件的目的,特别是在创建用户界面的环境中.我认为这是创建活动的原型:
public void EventName(object sender, EventArgs e);
Run Code Online (Sandbox Code Playgroud)
事件处理程序做了什么,为什么需要它们,以及如何创建一个?
什么是现实世界的地方呼吁代表?我很好奇这种方法是最佳解决方案的情况或模式.无需代码.
I never seem to understand why we need delegates? I know they are immutable reference types that hold reference of a method but why can't we just call the method directly, instead of calling it via a delegate?
Thanks
根据反if运动,最好不要在我们的代码中使用ifs.任何人都可以告诉我是否有可能摆脱这段代码中的if?(switch也不是一个选项,重点是删除条件逻辑,而不是用类似的语言结构替换ifs)
if(s == "foo")
{
Writeln("some logic here");
}
else if(s == "bar")
{
Writeln("something else here");
}
else if(s == "raboof")
{
Writeln("of course I need more than just Writeln");
}
Run Code Online (Sandbox Code Playgroud)
(语言:Java或C#)
我查看了一段旧代码,但无法理解以下内容:
public event EventHandler NameChanged;
#endregion
#region protected void OnNameChanged(EventArgs args)
/// <summary>
/// Raises NameChanged event.
/// </summary>
/// <param name="args">Event arguments.</param>
protected void OnNameChanged(EventArgs args)
{
EventHandler eh = this.NameChanged;
if (eh != null)
{
eh(this, args);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么通过调用委托来引发事件?难道我不能像往常一样简单地调用事件本身(NameChanged)吗?
编辑:我可以在MSDN上看到这也是建议:https://docs.microsoft.com/en-us/dotnet/standard/events/
我是C#的新手(我来自Java),我正在开发一个SharePoint项目.
我在代码中对此方法有以下疑问:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
lock (this)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
});
}
catch (Exception ex)
{
throw ex;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,此代码执行到delegate(){...} "block":
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
});
Run Code Online (Sandbox Code Playgroud)
这个delegate()方法的确切含义是什么?
在这里阅读:https://docs.microsoft.com/it-it/dotnet/csharp/language-reference/keywords/delegate
在我看来,它有点像一种声明"匿名"方法的方法,其中此方法的实现是{...}块中的代码.
这是正确的解释还是我错过了什么?
如果它是正确的,这个delegate()方法的pourpose是什么?为什么我没有将代码声明为经典方法?什么是精确的pourpose?