0

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

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

目前,我使用“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;
}

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

谢谢

4

3 回答 3

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";
于 2013-04-23T08:13:29.163 回答
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;
    }
}
于 2013-04-23T08:38:16.313 回答
0

我觉得if else if..应该够了。你这样做的方式,如果你重构你的代码并忘记最后break;你可能会面临更大的问题。

于 2013-04-23T08:14:57.643 回答