2010-08-22 97 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