Is there any difference in Console.WriteLine("{0}, var)

本文关键字:var quot difference any there in Console WriteLine Is | 更新日期: 2023-09-27 18:12:13

下面的语句是否有错误?

var str = "Hello how are you.";
MessageBox.Show("{0}",str);

我的问题是在下面的代码中,我没有正确地得到它。下面的代码是学习过程的一部分。在MessageBox中,"指定"变量没有像我上面所说的那样出现!我最初张贴它,由于我的无知,当我测试的东西,我可以使用MessageBox像控制台。writeline()。

abstract class Employee //Abstract class
{
     public virtual void WhichCoEmployee()
     {
         MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation); //My problem was in this line.
          //designation varaiable was not received in 
          //placeholder {0} for display in MessageBox.Show.
     }
     public void Designation(string desig)
     {
         designation = desig;
     }
     public string designation { get; set; }
}
class CEO : Employee //Inheritance
{
    public void Name()
    {
        MessageBox.Show("My name is Satheeshkumar K");
    }
}
 private void button2_Click(object sender, EventArgs e)
 {
     CEO ceo = new CEO(); //Initializing the CEO class.
     ceo.Name();
     ceo.Designation("CEO");   
     ceo.WhichCoEmployee();
 }

随后我纠正了MessageBox。通过更改显示问题消息框代码

MessageBox.Show("I am employed in XYZ Corporation as its " + designation);

效果很好。对此我没有更多要说的。由于其他成员的帮助,成为stackoverflow的一员确实帮助我学到了一些东西。

Is there any difference in Console.WriteLine("{0}, var)

EDIT:

简单地改变

MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation);

MessageBox.Show("I am employed in XYZ Corporation as its " + designation);

顺便说一句,你需要在某个地方调用这个方法来运行代码!


。根据语法,您的两行似乎是完全正确的

但是看起来你想要达到的和你已经做过的不一样。事情是这样的:你刚刚调用了MessageBox类的Show方法的重载版本,它接受两个字符串。

public static DialogResult Show(string text, string caption);

因此,在您的示例中,将显示一个带有"{0}"文本和"Hello how are you."标题的消息框。

Console.WriteLine("{0}", var);则完全不同。它用于将输出输出到控制台。它也有许多重载的变量,在这种情况下,它将用var变量的值替换{0}。因此,"Hello how are you."将被输出到控制台。