C# 发送HTML参数和文件路径参数?

C# 发送HTML参数和文件路径参数?,c#,methods,arguments,class-design,C#,Methods,Arguments,Class Design,我正在创建一个需要打印HTML字符串和HTML文档的printer类。所以基本上它可以得到: Printer.Print("<b>Hello world</b>"); 因此,在设计类的打印方法定义时,我将在以下两个方面进行选择: public static void Print(string inputString, string mode){ if(mode=="htmlString"){//Print the string itself} else

我正在创建一个需要打印HTML字符串和HTML文档的printer类。所以基本上它可以得到:

Printer.Print("<b>Hello world</b>");
因此,在设计类的打印方法定义时,我将在以下两个方面进行选择:

public static void Print(string inputString, string mode){
    if(mode=="htmlString"){//Print the string itself}
    else if(mode=="htmlFile"){//Print the document in the filepath}
}


一般来说,哪种做法更好?第一个选项需要另一个不是很好的参数,但是如果我们使用第二个选项,如果我们打算实际打印一个文件,但是使用了错误的文件名,那么它将打印错误的东西

很多时候,意外事件的发生空间太大,特别是在这种情况下,您必须确定如何根据输入采取行动,然后进一步进行验证处理(即File.Exists),这就需要误报。在我看来,应该这样做:

public static void PrintString(string input)
{
    //print the string, knowing precisely this is the intent,
    //and if not, it's what you're going to do anyway!
}

public static void PrintFile(string fileName)
{
    //no qualms here, you're going to print a file
}

我建议你采用失望先生建议的设计

然而,如果出于任何原因,你想保留原来的想法,我会做一点小小的改动。而不是将模式作为字符串传递,而是将其作为枚举传递。事实上,你也可以将失望先生的建议与此联系起来。比如说

public enum PrintMode
{
  File,
  Raw
}

public static void Print(string printData, PrintMode mode)
{
  if(mode == PrintMode.Raw)
  {
    //Print the string itself
  }
  else if (mode == PrintMode.File)
  {
    //Print the document in the filepath
  }
  else
  {
    throw new ArgumentException("Invalid print mode specified");
  }
}

public static void PrintString(string input)
{
  Print(input, PrintMode.Raw);
}

public static void PrintFile(string input)
{
  Print(input, PrintMode.File);
}

您的第二个想法是一个坏主意,因为每当用户打印原始字符串时,您都会执行不必要的文件系统检查。更重要的是,它可能会抛出异常,因为在打印原始字符串时,这将不是有效的文件路径。因此,
存在
检查可能会失败。

我同意使用两种方法是最好的方法。但是,.Net约定将具有以下方法名称:

public static void Print(string path) { ... }
public static void PrintHtml(string html) { ... }

我在寻找一个“最佳实践”的答案。从“最佳实践”的角度来看,这是正确的答案吗?我不得不说是的——虽然我没有听到福音之类的东西,但让我们看看其他人怎么想。这样就没有if's或but's或中间的任何东西,代码是显式的。即使两者都只是简单地调用一个内部助手方法,该方法完成了大量工作,但对用户来说是隐藏的,也可以避免让他们感到困惑(或者在离开时不得不阅读文档,寻找一种可以说明问题的方法)。为用户构建外观看起来很聪明,然而,构建完成几个不同任务的方法可能会变得非常混乱,而它们的名称并不能告诉您它们到底在做什么。在这种情况下,打印一个简单的字符串和打开和关闭一个文件有很大的区别(和影响)。首先,只包含文件名纯文本的HTML怎么样?在您的示例中,我无法将简单的文件路径打印为字符串。很好的一点,我并没有从这个角度考虑太多。我想再次告诉您失望先生的答案,这很清楚,而且对于某些东西应该如何表现也没有任何混淆。
public enum PrintMode
{
  File,
  Raw
}

public static void Print(string printData, PrintMode mode)
{
  if(mode == PrintMode.Raw)
  {
    //Print the string itself
  }
  else if (mode == PrintMode.File)
  {
    //Print the document in the filepath
  }
  else
  {
    throw new ArgumentException("Invalid print mode specified");
  }
}

public static void PrintString(string input)
{
  Print(input, PrintMode.Raw);
}

public static void PrintFile(string input)
{
  Print(input, PrintMode.File);
}
public static void Print(string path) { ... }
public static void PrintHtml(string html) { ... }