gpt4 book ai didi

c# - 返回方式一览

转载 作者:太空宇宙 更新时间:2023-11-03 19:21:56 25 4
gpt4 key购买 nike

我正在寻找以下模式:

我有几个这样的方法:
1. private bool CheckIfStringExist(string lookupString, ref string errorMessage)
2. private bool NumbersAreEqual(int one, int two, ref string errorMessage)
...
(其中大约 15 个)。

我想做的是以特定顺序运行它们,并在其中任何一个失败时向用户输出错误消息。我还想向用户显示方法友好名称。

到目前为止,我想到了以下内容。

我创建了一个类来分别保存每个方法:

public class CheckingMethod
{
public string name {get; set;}
public Action method {get; set;}
public bool success {get; set;}

public CheckingMethod(string name, Action method)
{
this.name= name;
this.method = method;
this.success = false;
}
}

这让我可以将所有方法存储在一个列表中...像这样:

List<CheckingMethod> cms = new List<CheckingMethod>();
cms.Add(new CheckingMethod("Check if text exist", ()=>CheckIfStringExist(lookupString, ref errorMessage);
cms.Add(new CheckingMethod ("Check if numbers are equal", ()=>NumbersAreEqual(num1, num2, ref errorMessage);

然后我可以像这样一个一个地运行它们:

foreach (CheckingMethod cm in cms)
{
cm.method()
}

不幸的是,Action 只返回 void 类型,所以我无法判断我的方法是返回 false 还是 true。此外,如果之前返回 false,我需要禁止运行下一个方法(尽管并非总是如此,只是在某些情况下)。

最佳答案

Action 只是一个委托(delegate),它被设计为在没有返回类型的情况下使用

但是您可以将 Action 委托(delegate)更改为 Func 委托(delegate)

public Func<bool> method {get; set;}

Also, I need to prohibit running of the next method if previous returned false (not always though, just in some cases).

解决这个问题的一种方法是:

  1. 向您的类添加一个属性,以确定如果返回类型不正确时是否应运行下一个方法

    public bool RunNextMethodIfConditionFails {get; set;}
  2. 在您的 foreach 循环中检查此属性:

    foreach (CheckingMethod cm in cms)
    {
    var res = cm.method();
    if (!res && !cm.RunNextMethodIfConditionFails)
    {
    // react to this case, throw an exception or exit the loop using break
    }
    }

关于c# - 返回方式一览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11621896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com