0

これは単なる「ベストプラクティス」の質問です...

入力文字列を受け取り、コンテンツに基づいて変更する必要がある関数がありますが、特定の条件が満たされると、それ以降のすべての処理が停止します。

現時点では、「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;
}

上記を達成するためのより「純粋な」方法はありますか?

ありがとう

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 を使用した 2 番目のバージョン。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 に答える