2010-08-22 160 views
1

讓我們假設我有一些對象使用的「輔助」方法。擴展與部分

private int MatchRegex(string regex, string input) 
    { 
     var match = Regex.Match(input, regex); 
     return match.Success ? Convert.ToInt32(match.Groups[1].Value) : 0; 
    } 

    private string Exec(string arguments, string path = "", bool oneLine = false) 
    { 
     var p = new Process(); 
     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.RedirectStandardOutput = true; 
     p.StartInfo.CreateNoWindow = true; 

     if (path != "") 
      p.StartInfo.WorkingDirectory = path; 

     p.StartInfo.FileName = "binary.exe"; 
     p.StartInfo.Arguments = arguments; 
     p.Start(); 

     string output = oneLine ? p.StandardOutput.ReadLine() : p.StandardOutput.ReadToEnd(); 
     p.WaitForExit(); 

     return output; 
    } 

你會選擇移出它們:另一個類,部分類或擴展方法?爲什麼?

回答

3

如果他們訪問私有狀態,他們必須是部分類片段中的方法。擴展方法非常有用,它可以支持對象的範圍,或者該類型不能用作部分類(接口是最有可能的示例,或者在組件之外)。

看着這些方法,它們似乎並沒有涉及任何給定的對象,所以我都不會這樣做,只是將它們作爲靜態方法暴露在實用程序類中。例如:

public static class ProcessUtils { 
    public static string Exec(...) {...} 
} 

正則表達式之一是不同的情況下;獲得組1作爲一個int似乎這樣的一個特定的場景(除非你的項目中有一些特定領域的東西使得這個公共場所),而且代碼是如此微不足道,我只是讓調用代碼使用現有的靜態Regex.Match。特別是,我希望調用者考慮靜態預編譯的正則表達式是否合適,您的實用工具方法不允許。

+0

同意你對'Exec'的回答,但是根本無法得到你對靜態'Regex.Match'和'MatchRegex'方法的意義。 – zerkms 2010-08-22 09:30:13

+0

明白了,很好的答案。似乎是最佳的。 – zerkms 2010-08-22 09:36:02