评估一系列条件并在条件满足时停止

时间:2013-04-23 08:10:53

标签: c# asp.net winforms

这只是一个“最佳实践”问题......

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

目前,我使用“while(true)”循环,然后当我得到我想要的东西时“休息”,下面是伪代码..

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;
}

是否有更“纯粹”的方式来实现上述目标?

由于

3 个答案:

答案 0 :(得分:4)

您应该在此处使用标准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";

答案 1 :(得分:1)

正如你所说,这只是一个更大问题的一个简单例子,我可能会这样做(当然这对于一个小例子来说太过分了,但它的扩展性非常好):

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;
    }
}

答案 2 :(得分:0)

我认为if else if..应该足够了。你这样做的方式,如果你重构代码并忘记上一个break;,你可能会面临更大的问题。