在十进制上舍入扩展时出错 – 无法使用实例引用访问; 用类型名称来限定它
我已经多次使用扩展方法,并没有遇到这个问题。 任何人都有任何想法,为什么这会引发错误?
/// /// Rounds the specified value. /// /// The value. /// The decimals. /// public static decimal Round (this decimal value, int decimals) { return Math.Round(value, decimals); }
用法:
decimal newAmount = decimal.Parse("3.33333333333434343434"); this.rtbAmount.Text = newAmount.Round(3).ToString();
newAmount.Round(3)抛出了编译器错误:
Error 1 Member 'decimal.Round(decimal)' cannot be accessed with an instance reference; qualify it with a type name instead
这里的冲突是你的扩展方法和decimal.Round
之间的冲突。 如已经发现的,这里最简单的解决方案是使用不同的名称。 类型的方法总是优先于扩展方法,甚至与static
方法冲突。
很抱歉能够快速回答我自己的问题。 在发布此内容的一秒钟内,我突然意识到编译器可能不喜欢“Round”作为名称。 所以我把它改成了“RoundNew”,它起作用了。 我想某种命名冲突……’
没有错误了:
/// /// Rounds the specified value. /// /// The value. /// The decimals. /// public static decimal RoundNew (this decimal value, int decimals) { return Math.Round(value, decimals); } decimal newAmount = decimal.Parse("3.33333333333434343434"); this.rtbAmount.Text = newAmount.RoundNew(3).ToString();