我在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;
}
那么如何从一个引用文本中应该是字符串的数组位置的方法返回一个字符串?
答案 0 :(得分:4)
你应该像这样使用string.Format:
searchResult = string
.Format("Account # {0} has a balance of {1:c} for customer {2}",
accountsarr[i], balancesarr[i], namesarr[i]);
你得到的错误是句法错误,你有一个逗号而不是+
和一个额外的"
您知道为什么您的代码没有编译:
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
答案 1 :(得分:2)
您可以执行以下操作:
searchResult = "Account #" + accountsarr[i] + " has a balance of "+String.Format("{0:c}",balancesarr[i]) + " for customer " + namesarr[i];