正确使用

本文关键字: | 更新日期: 2023-09-27 18:12:26

对于这段代码,它只显示了Net Pay(最后一行代码)。我想我应该做一些像lblDisplay.Text = "Gross Pay: " + grossPay;'n"State Income Tax Deduction: " + stateIncome;,但它不工作,因为它说"/"是一个意想不到的字符。

这些都没有让我感到惊讶,因为每当我之前使用'n时,它总是在"里面。但是如果最后是+ grossPay;,我怎么让n起作用呢?

        lblDisplay.Text = "Gross Pay: " + grossPay;
        lblDisplay.Text = "State Income Tax Deduction: " + stateIncome;
        lblDisplay.Text = "Federal Income Tax Deduction: " + federalIncome;
        lblDisplay.Text = "Social Security Deduction: " + socialSecurity;
        lblDisplay.Text = "Medicare Deduction: " + medicare;
        lblDisplay.Text = "Net Pay: " + netPay;

正确使用

这是使用string.Format更好的编码,节省了一些输入,并减少了字符串格式化错误的机会:

lblDisplay.Text = string.Format(
        "Gross Pay: {0} " +
        "'nState Income Tax Deduction: {1}" +
        "'n Federal Income Tax Deduction: {2}" +
        "'n Social Security Deduction: {3}" +
        "'n Medicare Deduction: {4}" +
        "'n Net Pay: {5}", 
        grossPay, stateIncome, federalIncome, socialSecurity, medicare, netPay);

或者,如果您不喜欢所有这些加号和'n:

lblDisplay.Text = string.Format(
@"Gross Pay: {0} 
State Income Tax Deduction: {1}
Federal Income Tax Deduction: {2}
Social Security Deduction: {3}
Medicare Deduction: {4}
Net Pay: {5}", 
grossPay, stateIncome, federalIncome, socialSecurity, medicare, netPay);

或者c# 6.0中的$@语法,如果你能用的话。

如果您想用字符串制作多行,我建议您使用$@""字符串。这将允许您执行如下操作:

lblDisplay。Text = $@"GrossPay: {GrossPay}州所得税扣除:{stateIncome}";

@允许您制作多行字符串,$允许您插入字符串,使用{}中的表达式将在字符串中替换它们。

注意$前缀是c# 6.0的一个特性。如果您无法访问此功能,我会查看string.Format(string, params object[])

我认为你需要这样做:

 lblDisplay.Text = "Gross Pay: " + grossPay;
 lblDisplay.Text += "'n State Income Tax Deduction: " + stateIncome;
 lblDisplay.Text += "'n Federal Income Tax Deduction: " + federalIncome;
 lblDisplay.Text += "'n Social Security Deduction: " + socialSecurity;
 lblDisplay.Text += "'n Medicare Deduction: " + medicare;
 lblDisplay.Text += "'n Net Pay: " + netPay;

按照编写的代码,在每一行上为lblDisplay.Text分配一个新值。

我更喜欢带有多行字面值字符串的Abels Answer,但我将向您介绍Environment。换行符

lblDisplay.Text = "Gross Pay: " + grossPay;
lblDisplay.Text += Environment.NewLine + "State Income Tax Deduction: " + stateIncome; //Etc
相关文章:
  • 没有找到相关文章