c# 是否可以创建这样的委托(delegate)?

标签 c# .net delegates

我有一个想法,听起来好像可行,但我不完全确定,因此就是否可以实现以及如何实现寻求建议。

在我的网络表单上,我有一个名为“error”的 bool 值。

页面上需要发生许多事情才能成功加载。

我可以这样写代码:

bool thisSuccess = DoThis();
if(!thisSuccess)
    then error;

bool thatSuccess = DoThat();
if(!thatSuccess)
    then error;

if(error)
  FailoverActions();

等等。

当然那会是完全低效的,所以我认为创建某种委托(delegate)可能是可行的,代码看起来像这样:

错误 = DoThis();

...还有某种触发器,它在 error = true 时调用函数;

很抱歉缺乏精确的细节,但这对我来说是新的领域。


更新

感谢大家的好主意。

之所以没有详细说明,是因为我经验不足,而我迄今为止发现的 .net 是,尽管有很多方法可以打鸡蛋,但总的来说有一些比其他方法更好。

我很欣赏你有经验的观点。

再次感谢。

最佳答案

为什么不呢。返回分配给被委托(delegate)者的 bool 值的方法。

这边

public delegate bool PerformCalculation();

PerformCalculation = DoThis();
if (!PerformCalculation())
    then error;

PerformCalculation = DoThat();
if(!PerformCalculation())
    then error;

if(error)
    FailoverActions();

替代解决方案

不需要委托(delegate)。只需2个方法

bool DoThis()bool DoThat()

if (!DoThis())
    then error;

if(!DoThat())
    then error;

if(error)
    FailoverActions();

关于c# 是否可以创建这样的委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367335/

相关文章:

c# - Selenium C# 如何暂停/播放嵌入式 youtube 视频

c# - 使用C#/.Net Core签署Powershell脚本

c# - C# 编译器可以编译 VB.Net 代码吗?

c# - 为什么 UInt16 数组的加法速度似乎比 int 数组快?

c# - 委托(delegate)和跨线程异常

ios - 将 TextField 输入限制为大写字母、数字和 6 个字符限制?

c# - 从 F# 查看 C# Windows 窗体项目代码

c# - 运行时的 .NET CLR/Framework 检测

c# - OpenFileDialog 在 Windows 7 中不显示完整的文件名

ios - TableView :numberOfRowsInSection:]: unrecognized selector sent to instance