0

たとえば、次のパターンがあります:
- Out{d}bytes
- In{d}bytes
- In{d}bytesOut{d}bytes
- Out{d}words
- In{d}words
- In{d}wordsOut {d} 語({d} は数字)。

私はのファンではありませんcase。このテキストに従って、次のような形式を作成するにはどうすればよいですか。

p => p.Out == 8 && p.In == 16 //In8bytesOut16bytes  
p => p.Out == 8*8 && p.In == 4*8 // In8Out4words  
p => p.In == 8 // In8bytes  

正規表現?どんなアドバイスも役に立ちます。前もって感謝します。

Match match;  
int inBytes = 0;  
int outBytes = 0;    
string pattern =   
@"(?<InOut>In|Out)(?<inBytes>\d+)bytes((?<Out>Out)(?     <outBytes>\d+)bytes)?";  
Func<string, IService, bool> predicate;  
match = Regex.Match(description, pattern);  
if ((match.Groups[4].Length > 0))  
{  
   int.TryParse(match.Groups[3].Value, out inBytes);  
   int.TryParse(match.Groups[5].Value, out outBytes);  
   predicate = p => p.In == inBytes && p.Out == outBytes;  
}  

入力はフォーマットされた文字列で、ファイルから取得されます。上記のパターンのいずれかを満たす必要があります。主なアイデアは、この文字列から数値を取得することです。バイト単位のInOutの2 つの定義を含むサービスがあります。この文字列を解析して条件を作成する必要があります。
たとえば、In4bytesOut8bytes を取得します。4と8を取得して
、次のような条件を作成する必要がありますFunc<string, IService, bool> predicate = p => p.In == 4 && p.Out == 8

4

1 に答える 1

0

ここでは、ラムダの代わりに仕様パターンを使用することをお勧めします。

public class ServiceSpecification
{
    private const int BytesInWord = 8;
    public int? In { get; private set; }
    public int? Out { get; private set; }

    public static ServiceSpecification Parse(string s)
    {
        return new ServiceSpecification {
            In = ParseBytesCount(s, "In"),
            Out = ParseBytesCount(s, "Out")
        };
    }

    private static int? ParseBytesCount(string s, string direction)
    {
        var pattern = direction + @"(\d+)(bytes|words)";
        var match = Regex.Match(s, pattern);
        if (!match.Success)
            return null;

        int value = Int32.Parse(match.Groups[1].Value);
        return match.Groups[2].Value == "bytes" ? value : value * BytesInWord;
    }

    public bool IsSatisfiedBy(IService service)
    {
        if (In.HasValue && service.In != In.Value)
            return false;

        if (Out.HasValue && service.Out != Out.Value)
            return false;

        return true;
    }
}

入力文字列から仕様を作成できます。

var spec = ServiceSpecification.Parse(text);

そして、サービスがこの仕様を満たすかどうかのチェック:

var specs = new List<ServiceSpecification>
{
    ServiceSpecification.Parse("In8bytesOut16bytes"),
    ServiceSpecification.Parse("In8wordsOut4words"),
    ServiceSpecification.Parse("In8bytes")
};

foreach(var spec in specs)
    Console.WriteLine(spec.IsSatisfiedBy(service));
于 2013-09-09T11:27:39.723 に答える