C# 为什么我不能写MessageBox.Show(";asdfasdf{0}";,I);?
我觉得这是最痛苦的,也是最令人衰弱的。一个有效,另一个无效?这种行为不一致的根源是什么?我想得越多,我能想象的就越少,不理解往往会变成自我厌恶 Show()方法没有适当的重载 为了方便起见,它被添加到了Console.WriteLine,但它不是每个.NET方法的组成部分 要达到相同的效果,请手动使用C# 为什么我不能写MessageBox.Show(";asdfasdf{0}";,I);?,c#,windows,C#,Windows,我觉得这是最痛苦的,也是最令人衰弱的。一个有效,另一个无效?这种行为不一致的根源是什么?我想得越多,我能想象的就越少,不理解往往会变成自我厌恶 Show()方法没有适当的重载 为了方便起见,它被添加到了Console.WriteLine,但它不是每个.NET方法的组成部分 要达到相同的效果,请手动使用string.Format: int i = 85; Console.WriteLine("My intelligence quotient is {0}", i); // Kosher Mes
string.Format
:
int i = 85;
Console.WriteLine("My intelligence quotient is {0}", i); // Kosher
MessageBox.Show("My intelligence quotient is {0}", i); // Not Kosher
为什么很难说(这只是MS是如何定义的),但如果您想为这两种情况编写“一致”的代码,那么您可以使用如下示例:MessageBox.Show(string.Format("asdfasdf{0}", i)); // Kosher
或
WriteLine()
方法有重载,而MessageBox.Show()
没有重载。相反,您需要使用:
Console.WriteLine (string.Format ("asdfasdf{0}", i)); // although this is unneccesary!
Console.WriteLine
、Debug.Print
等都是打算接受字符串以将其写入特定位置的方法<代码>MessageBox.Show是一种向用户显示MessageBox模式的方法。还有很多选项需要设置(如标题、按钮等),因此此时接受格式逻辑是没有意义的
HTH控制台。Writeline具有以下重载:
string.Format
来获得类似的效果:
MessageBox.Show(string.Format("asdfasdf{0}", i));
或者,如果这对您非常重要,您可以创建自己的类,并将其用于您已经要求的用途:
public void ShowMessageBox(string format, params object[] args)
{
MessageBox.Show(string.Format(format, args));
}
// ...
ShowMessageBox("You entered: {0}", someValue);
public void ShowMessageBox(string format, params object[] args)
{
MessageBox.Show(string.Format(format, args));
}
// ...
ShowMessageBox("You entered: {0}", someValue);
class myMessageBox
{
private myMessageBox()
{ }
public static void Show(string text,params object[] i)
{
text = String.Format(text, i);
MessageBox.Show(text);
}
}