skm*_*asq 6 c# interface class
我希望传递string或List<string>作为参数传递,就像我在JavaScript中可以做的那样,然后评估它的类型并执行适当的操作.现在我可以这样做:
public static class TestParser
{
static void Parse(string inputFile)
{
// Lots of code goes in here
}
static void Parse(List<string> inputFileList)
{
// Lots of code goes in here too
}
}
Run Code Online (Sandbox Code Playgroud)
这些方法中的代码是什么,基本上解析一些程序或一个文件或文件列表,取决于给出的类型.
如果我有很多代码,我应该复制它,还是应该创建包含代码的sub方法,还是有另一种很酷的方式我可以在c#中执行此操作?
Eri*_* J. 11
取决于Parse()应该做什么,合理的模式可能是
static void Parse(string inputFile)
{
// Lots of code goes in here
}
static void Parse(List<string> inputFileList)
{
foreach (var inputFile in inputFileList)
Parse(inputFile);
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
已建议使用替代方法来创建new List<string>() { inputFile}和调用,Parse(List<string>)而不是将处理代码分离为单独的方法.
static void Parse(List<string> inputFileList)
{
// Lots of code goes in here too
}
static void Parse(string inputFile)
{
Parse(new List<string>() { inputFile });
}
Run Code Online (Sandbox Code Playgroud)
几乎在所有情况下,这只是一个风格问题.我更喜欢我的解决方案,因为乍一看(至少对我来说)更清楚,因为我已经在非常高容量的系统上工作,其中CLR处理短期对象的能力成为性能问题.99.99%的性能关键应用程序不会遇到该特定问题.
任何性能差异只会在您将CLR的CG推到断点时进行如此大量的单独调用时才会显现.如果您对该方法的调用量适中甚至很高,那么// Lots of code goes in here处理时间可能会使创建新列表的性能成本几乎无法估量.
对于几乎所有情况,这两种方法仅在风格上有所不同,并且都是合适的.