0

我在 main 中调用并包含在同一个类中的方法遇到问题。该方法正在输出一个字符串值,我的问题是试图在字符串消息中包含对数组的引用。我收到消息

只有赋值、调用、递增、递减和新对象表达式可以用作语句"

以及关于逗号和一大堆 ; 的无效表达。预期所有关于以下行:

searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}" + " for customer " + namesarr[i], balancesarr[i]";

全部在以下方法中:

public static string searchAccounts(ref int AccountNumber, int[] accountsarr, double[] balancesarr, string[] namesarr)
{
    bool isValidAccount = false;
    int i = 0;

    while (i < accountsarr.Length && AccountNumber != accountsarr[i])
    {
        ++i;
    }

    if (i != accountsarr.Length)
    {
        isValidAccount = true;
    }

    string searchResult;

    if (isValidAccount)
    {
        searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}" + " for customer " + namesarr[i], balancesarr[i]";
    }
    else
        searchResult = "You entered an invalid account";

    return searchResult;
}

那么如何从一个方法返回一个字符串,该方法引用了文本中应该是字符串的数组位置?

4

2 回答 2

4

您应该像这样使用string.Format

 searchResult = string
        .Format("Account # {0} has a balance of {1:c} for customer {2}",
         accountsarr[i], balancesarr[i], namesarr[i]);

你得到的错误是语法错误,你有一个逗号而不是 a+和一个额外的"

只是你知道为什么你的代码没有编译

searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}" 
     + " for customer " + namesarr[i], balancesarr[i]"; << this is an extra "
                                   //^ you cannot put a comma here
于 2012-04-04T04:49:35.460 回答
2

您可以简单地执行以下操作:

searchResult = "Account #" + accountsarr[i] + " has a balance of "+String.Format("{0:c}",balancesarr[i]) + " for customer " + namesarr[i];
于 2012-04-04T04:48:54.050 回答