cdj*_*cdj 3 c# if-statement visual-studio
我是新手,所以请耐心等待,我对if声明有点麻烦.
如果textbox 2超过0.5,我想在文本框1中打印一条消息.任何人都可以帮忙.
class Product
{
public string collectmessage1()
{
return "Collect your product";
}
if (txtMoney.Text > 0.5)
{
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Run Code Online (Sandbox Code Playgroud)
小智 6
TextBox.Textproperty返回一个String无法与a 0.5,一个double对象进行比较的属性.使用您的代码将引发错误
Error1运算符'>'不能应用于'string'和'double'类型的操作数
在比较之前将文本框的text属性返回的字符串解析为double,您将消除此错误.正如Velous所说,在格式异常的情况下,TryParse是更好的选择.
double no;
bool valid = double.TryParse(txtMoney.Text, out no);
if (valid && no > 0.5) {
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Run Code Online (Sandbox Code Playgroud)