举个例子:
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));(1)为什么在C#中我们总是需要把.ToString()放在正确的地方?
(2) Convert.To...它不会产生不必要的管理费用吗?
在下面给出的代码中:在接受用户输入后,它给出错误:“输入字符串格式不正确”。
// Main begins program execution.
public static void Main()
{
Customer customer = new Customer();
// Write to console/get input
Console.Write("Enter customer's salary: ");
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
Console.WriteLine("Salary in class variable is: {0}", customer.Salary.ToString());
Console.Read();
}
class Customer
{
public Decimal Salary { get; set; }
}同样,我必须使用以下两种方法:
string sal = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
customer.Salary = Convert.ToDecimal(sal);或者,我必须在Customer类中更改数据类型本身。
泛型中的任何东西都可以避免这种开销吗?
发布于 2010-10-28 23:50:06
我认为如果您使用Decimal.Parse或Decimal.TryParse进行转换,而不是依赖Convert.ToDecimal,您会更高兴。你可以这样写:
Decimal tempSal;
string sal = Console.ReadLine();
if (Decimal.TryParse(sal, out tempSal))
{
customer.Salary = tempSal;
}
else
{
// user entered bad data
}https://stackoverflow.com/questions/4044541
复制相似问题