Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用ToString格式化输出_C#_Format_Output_Tostring - Fatal编程技术网

C# 使用ToString格式化输出

C# 使用ToString格式化输出,c#,format,output,tostring,C#,Format,Output,Tostring,我试图用C编辑我的燃油消耗行,以便在数字量之后输出单词gallons。我不知道如何操纵ToString来实现这一点。任何帮助都将不胜感激 // toString method to display object information public override string ToString() { return "\n\nDestination: " + destinationCity + "\n\nTotal Miles

我试图用C编辑我的燃油消耗行,以便在数字量之后输出单词gallons。我不知道如何操纵ToString来实现这一点。任何帮助都将不胜感激

    // toString method to display object information
    public override string ToString()
        {  return "\n\nDestination: " + destinationCity +
                "\n\nTotal Miles: " + mileageRoundTrip.ToString("F0") +
                "\n\nFuel Consumed: " + gallonsUsed.ToString("F1") +
                "\n\nFuel Cost Per Gallon: " + gallonsCost.ToString("C") +
                "\n\nTotal Fuel Cost for this Trip: " + totalFuelCost.ToString("C") +
                "\n\nMPG: " + amountMPG.ToString("F0") +
                "\n\nFuel Cost Per Mile: " + costPerMile.ToString("C"); }

与您正在执行的串联类似,您可以在变量之后但在任何换行符之前插入另一个由加号+运算符包围的字符串文字,这将在数值之后放置度量单位。例如:

+ " gallons" +
编辑:
GreagoryABeamer在他的文章中提出了一些好的观点,他为打印单元添加了一个健壮、系统的实现。我的解决方案不是这样的,如果这完全是生产代码或重复代码,那么这是一个更好的答案。然而,这个解决方案确实提供了快速使用和不存在开销的机会,我相信字符串文字在C和C++中在编译时被连接起来。通过一些变量和文字的对齐,代码看起来也非常干净。也许有点孩子气,但有时我更喜欢快速简单

首先,如果您真的想尝试使用这种方法,那么应该使用StringBuilder而不是Concatenating。不,concats不会让事情慢那么多,但是你在幕后创造了很多额外的字符串来得到你想要的

至于添加,您可以这样做:

public override string ToString()
{  var builder = new StringBuilder();
   /// more lines here
   builder.Append(gallonCost.ToString("C"));
   builder.Append(" gallons\n\n");
   // etc
   return builder.ToString();
}
您还可以为每个项目创建内部帮助器方法,以按您所需的方式对其进行格式化,然后在生成器中连接它们。它更干净

但是,从建筑学的角度来看,这样做有很多气味。更改ToString的原因是将对象的表示形式从默认更改为默认,而不是格式化用户界面的信息。如果这就是动机,你最好通过另一个物体来避免气味,除非你制定了一个规则,所有物体的行为方式都是一样的,仍然不是很好,但是一致性更容易遵循

如果这是一个一次性或临时的应用程序,你可能会侥幸逃脱。如果是私人的,那是你自己的事,所以做你想做的。对于企业软件,我会在代码审查中对此进行标记,并强制某人告诉我他们为什么使用此特定模式,因为它是非标准的,并且可能违反最佳实践。

更新:请参阅@mvarta的答案,该答案将格式与StringBuilder相结合,以获得更具可读性的解决方案

我发现String.format更具可读性,因为您将整个模板编写为一个字符串:

return String.format(
    "\n\nDestination: {0}\n\nTotal Miles: {1:F0}\n\nFuel Consumed: {2:F1} gallons\n\nFuel Cost Per Gallon: {3:C}\n\nTotal Fuel Cost for this Trip: {4:C}\n\nMPG: {5:F0}\n\nFuel Cost Per Mile: {6:C}", 
    destinationCity, 
    mileageRoundTrip, 
    gallonsUsed, 
    gallonsCost, 
    totalFuelCost, 
    amounts, 
    costPerMile
);
若要在任何地方添加加仑,只需将其写入模板即可

变量在模板中用{0}、{1}等表示,其中数字是变量在以下参数中的位置

toString调用中的所有特定格式也会使用{0:C}、{1:F1}等嵌入到模板中。string.Format正在为您调用toString,因此不会太冗长


如果您想保留包含两个换行符的原始格式,这应该以更节省内存的方式实现,同时为您提供所需的加仑后缀

var sb = new StringBuilder();
sb.AppendFormat("\n\nDestination: {0}", destinationCity);
sb.AppendFormat("\n\nTotal Miles: {0:F0}", mileageRoundTrip);
sb.AppendFormat("\n\nFuel Consumed: {0:F1} gallons", gallonsUsed);
sb.AppendFormat("\n\nFuel Cost Per Gallon: {0:C}", gallonsCost);
sb.AppendFormat("\n\nTotal Fuel Cost for this Trip: {0:C}", totalFuelCost);
sb.AppendFormat("\n\nMPG: {0}", amountMPG);
sb.AppendFormat("\n\nFuel Cost Per Mile: {0:C}", costPerMile);
return sb.ToString();

您现在面临的问题是什么?有效,但它会加剧创建其他字符串以返回对象的不同字符串视图的过程,并且仍然使用反模式。这是最好的解决方案。非常可读,因为代码行与输出行匹配,并且格式化代码被最小化。感谢@Mvarta扩展我的知识!: