在我的richtextbox中显示int解决方案时,很难将其转换为String类型


private void Convert_Click(object sender, EventArgs e)
{
int solution;
String value = "";
//double pound = 20.09;
double rand = (double.Parse(value));
if (pound.Checked == true)
{
solution = (int)(rand * 20.09);
rich.Text = Convert.toString(solution);
}
else if (dollar.Checked == true)
{
solution = (int)(rand * 16.92);
rich.Text = Convert.toString(solution);
}
else if (euro.Checked == true)
{
solution = (int)(rand * 17.06);          
rich.Text = Convert.toString(solution); 
// The error I receive is that no overload methods for "Tostring" takes 1 argument 
}
}

您的代码有几个问题。第一个是语法

Convert.toString(solution); // <- doesn't compile

当编译器像一样抱怨

。。。"无过载"方法;toString"接受1个参数。。。

这意味着具有此类签名的方法不存在。原因通常是打字错误、参数顺序或类型错误、额外参数等。

这里有一个打字错误。正确的语法是Convert.ToString(solution);,注意大写To,而不是to

另一个问题是在一开始:

String value = "";
//double pound = 20.09;
// the next line will throw exception, "" can't be parsed into a double
double rand = (double.Parse(value)); // <- runtime problem here 

你应该从一些TextBoxRichEdit等读取值,比如

String value = myTextBox.Text;

最后,不要重复自己:你不必放那么多Convert.ToString;如果

您提取业务逻辑作为属性/方法(CurrencyRate(,您可以拥有

private double CurrencyRate {
get => pound.Checked  ? 20.09 
: dollar.Checked ? 16.92
: euro.Checked   ? 17.06
: double.NaN;  
}
private void Convert_Click(object sender, EventArgs e) {
if (double.TryParse(myTextBox.Text, out var rand) && !double.IsNaN(CurrencyRate)) 
rich.Text = $"{(int)(rand * CurrencyRate)}";
}

在这里,我保留了您的截断为int-$"{(int)(rand * CurrencyRate)}",但当使用货币时,您可能希望用小数点后的两位数字表示结果:$"{rand * CurrencyRate:f2}"

最新更新