- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在寻找以下模式:
我有几个这样的方法:
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).
解决这个问题的一种方法是:
向您的类添加一个属性,以确定如果返回类型不正确时是否应运行下一个方法
public bool RunNextMethodIfConditionFails {get; set;}
在您的 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/
我有 Item 列表(某个类),这个类有 3 个变量 price、name 和 count. 我想知道如何删除所有价格为 320 的商品。 最佳答案 这个呢? std::list l; //... l
我是一名优秀的程序员,十分优秀!