C#编译报错:‘decimal’未包含‘Round’定义,求解决方案
解决‘decimal’ does not contain a definition for ‘Round’编译错误
嘿,这个问题我刚接触C#的时候也踩过坑,咱们来快速搞定它~
错误原因
你代码里写的decimal.Round是问题核心:虽然decimal是C#对System.Decimal类型的别名,但直接用小写的decimal调用静态方法Round会让编译器无法正确识别;另外如果你的代码顶部没有引用System命名空间,也会导致找不到这个方法。
两种解决办法
办法一:使用Decimal.Round(注意首字母大写)
Round是System.Decimal类的静态方法,你可以直接用大写的Decimal来调用(如果已经加了using System;),或者写全限定名:
private void totalPoundsTextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = textBoxes[1]; decimal numericValue = textBoxNumberCheck(textBox, 0M, 22046M,false); if (numericValue >= 0) weight.Kilos = Decimal.Round(numericValue / 2.2046M, 2, MidpointRounding.AwayFromZero); UpdateBoxValues(); }
如果代码顶部没有using System;,就改成全限定名调用:
weight.Kilos = System.Decimal.Round(numericValue / 2.2046M, 2, MidpointRounding.AwayFromZero);
办法二:使用Math.Round(更推荐)
System.Math类提供了专门处理decimal类型的Round重载,写法更直观,也不用纠结大小写问题:
private void totalPoundsTextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = textBoxes[1]; decimal numericValue = textBoxNumberCheck(textBox, 0M, 22046M,false); if (numericValue >= 0) weight.Kilos = Math.Round(numericValue / 2.2046M, 2, MidpointRounding.AwayFromZero); UpdateBoxValues(); }
同样要确保代码顶部有using System;,否则需要写成System.Math.Round(...)。
额外检查
别忘了确认代码文件的最顶部是否添加了这个命名空间引用:
using System;
内容的提问来源于stack exchange,提问作者Nigel Foster
相关产品推荐
相关产品推荐

