C# “给出错误”;输入字符串的格式不正确";
正如错误所说,您似乎在文本框中输入了无效字符串。例如,在文本框中输入“foo”,这将导致异常,因为您正在执行C# “给出错误”;输入字符串的格式不正确";,c#,C#,正如错误所说,您似乎在文本框中输入了无效字符串。例如,在文本框中输入“foo”,这将导致异常,因为您正在执行Convert.ToDouble(“foo”) 使用.TryParse sw.Start(); System.Net.FileWebResponse res = (FileWebResponse)req.GetResponse(); sw.Stop(); TimeSpan timeToLoad = sw.Elapsed; TextBox2.Text = timeToLoad.ToStri
Convert.ToDouble(“foo”)
使用.TryParse
sw.Start();
System.Net.FileWebResponse res = (FileWebResponse)req.GetResponse();
sw.Stop();
TimeSpan timeToLoad = sw.Elapsed;
TextBox2.Text = timeToLoad.ToString().Trim();
var a=1.1;
a = Convert.ToDouble(TextBox2.Text); //This is where the error is thrown
var threshold=5;
if (a > threshold)
{
Console.WriteLine("Scale up server");
}
else
{
Console.WriteLine("Scale down web server");
}
说明:检查字符串值是否可转换为双精度,并返回布尔值。它还将把值写入
out
参数中供我们使用。问题是Convert.ToDouble(TextBox2.Text)部分
似乎您想要比较经过的时间间隔而不是整个时间间隔,下面的代码片段应该可以避免您出错
var a=1.1;
Double.TryParse(TextBox2.Text, out a)
如果您想要记号或其他属性,也可以在TimeSpan上使用这些属性
Stopwatch sw = new Stopwatch();
TimeSpan t = sw.Elapsed;
double v =0;
Double.TryParse(t, out v);
这是一个糟糕的问题,你甚至还没有指出它在哪一行(虽然我有一个很好的猜测…)请尝试做一些研究。谷歌搜索这个错误应该会给你一个很好的答案。嘿,谢谢XXX,这很有效,但是你上面写的声明是什么意思??@GurjotSingh-解释added@GurjotSingh更重要的是,如果转换失败,
Parse
(这就是Convert.ToDouble
所使用的)就不会抛出(这完全是个例外……)
Stopwatch sw = new Stopwatch();
TimeSpan t = sw.Elapsed;
double v =0;
Double.TryParse(t, out v);
Stopwatch sw = new Stopwatch();
TimeSpan t = sw.Elapsed;
double v =0;
Double.TryParse(t.Ticks, v);