计算一系列条件并在条件满足时停止

本文关键字:条件 满足 一系列 计算 | 更新日期: 2023-09-27 18:10:31

这只是一个"最佳实践"的问题…

我有一个函数,它接受一个输入字符串,然后必须根据内容更改它,但是一旦满足特定条件,则所有进一步的处理都停止。

目前,我使用"while(true)"循环,然后当我得到我想要的东西时使用"break",下面是伪代码…

string Input = "xyz";
string Output = string.Empty;
while (true)
{
    if (Input.StartsWith("x"))
    {
        Output = "string starts with an X";
        break;
    }
    if (Input.Contains("y"))
    {
        Output = "string has a 'y' in it";
        break;
    }
    if (Input.IndexOf("z") == 2)
    {
        Output = "string has a 'z' as the 3rd character";
        break;
    }
    Output = "string does not match any conditions";
    break;
}

是否有更"纯粹"的方法来实现上述目标?

谢谢

计算一系列条件并在条件满足时停止

这里应该使用标准的if-ifelse-else

string Input = "xyz";
string Output = string.Empty;
if (Input.StartsWith("x"))
{
    Output = "string starts with an X";
}
else if (Input.Contains("y"))
{
    Output = "string has a 'y' in it";
}
else if (Input.IndexOf("z") == 2)
{
    Output = "string has a 'z' as the 3rd character";
}
else
{
    Output = "string does not match any conditions";
}

更新

第二个版本,使用LINQ。您可以创建条件函数和期望输出的List,然后使用FirstOrDefault获得第一个匹配条件。

string Input = "xyz";
string Output = string.Empty;
var conditionList = new List<Tuple<Func<string, bool>, string>>();
conditionList.Add(Tuple.Create<Func<string, bool>, string>((string x) => x.StartsWith("x"), "string starts with x"));
conditionList.Add(Tuple.Create<Func<string, bool>, string>((string x) => x.Contains("y"), "string has a 'y' in it"));
conditionList.Add(Tuple.Create<Func<string, bool>, string>((string x) => x.IndexOf("z") == 2, "string has a 'z' as the 3rd character"));
var firstMatch = conditionList.FirstOrDefault(x => x.Item1(Input));
Output = firstMatch != null ? firstMatch.Item2 : "string does not match any conditions";

正如你所说的,这只是一个更大问题的一个微不足道的例子,我可能会这样做(当然,对于一个小例子来说这是多余的,但它可以很好地扩展):

public interface ICondition
{
    bool IsMatch(string input);
    string GetMessage();
}
public class StartsWithTest : ICondition
{
    public bool IsMatch(string input)
    {
        return input.StartsWith("x");
    }   
    public string GetMessage()
    {
        return "string starts with an X";
    }
}

public class TestInput
{
    private readonly IList<ICondition> _conditions;
    public TestInput()
    {
        _conditions = new List<ICondition>();
        _conditions.Add(new StartsWithTest());
        //etc etc
    }
    public string Test(string input)
    {
        var match = _conditions.FirstOrDefault(c => c.IsMatch(input));
        if (match != null)
            return match.GetMessage();
        else
            return string.Empty;
    }
}

我认为if else if..应该足够了。按照您的做法,如果您重构代码并忘记了最后一个break;,您可能会面临更大的问题。