请帮我修复此错误。 [英] Please help me to fix this error.

查看:84
本文介绍了请帮我修复此错误。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

decimal DisCp = Convert.ToDecimal(txtDiscountedCashPrice.Text.Trim())* Convert.ToInt16(txtQuantity.Text.Trim());



我尝试过:



decimal DisCp = Convert.ToDecimal(txtDiscountedCashPrice.Text.Trim())* Convert.ToInt16(txtQuantity.Text。 Trim());

decimal DisCp = Convert.ToDecimal(txtDiscountedCashPrice.Text.Trim()) * Convert.ToInt16(txtQuantity.Text.Trim());

What I have tried:

decimal DisCp = Convert.ToDecimal(txtDiscountedCashPrice.Text.Trim()) * Convert.ToInt16(txtQuantity.Text.Trim());

推荐答案

简单:不要在用户输入上使用转换。

相反,使用适当的TryParse方法:

Simple: don't use Convert on user input.
Instead, use the appropriate TryParse methods:
decimal discountedCashPrice, quantity;
if (!decimal.TryParse(txtDiscountedCashPrice.Text.Trim(), out discountedCashPrice))
   {
   ... report problem to user
   return;
   }
if (!decimal.TryParse(txtQuantity.Text.Trim(), out quantity))
   {
   ... report problem to user
   return;
   }
decimal DisCp = discountedCashPrice * quantity;

如果用户输入错误,转换方法总是抛出异常 - 他们这样做,用户,所有的时间 - 但TryParse方法没有 - 他们允许你优雅地告诉用户问题是什么,并让他修复它而不是崩溃你的应用程序。

The Convert methods always throw an exception if the user enters something wrong - and they do that, users, all the time - but the TryParse methods don't - they allow you to gracefully tell the user what the problem is, and let him fix it instead of crashing your app.


这篇关于请帮我修复此错误。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆