在十进制上舍入扩展时出错 - 无法使用实例引用访问; 用类型名称来限定它

mse*_*dio 8 .net c# extension-methods rounding visual-studio-2010

我已经多次使用扩展方法,并没有遇到这个问题.任何人都有任何想法,为什么这会引发错误?

 /// <summary>
 /// Rounds the specified value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="decimals">The decimals.</param>
 /// <returns></returns>
 public static decimal Round (this decimal value, int decimals)
 {
     return Math.Round(value, decimals);
 }
Run Code Online (Sandbox Code Playgroud)

用法:

decimal newAmount = decimal.Parse("3.33333333333434343434");
this.rtbAmount.Text = newAmount.Round(3).ToString();
Run Code Online (Sandbox Code Playgroud)

newAmount.Round(3)抛出了编译器错误:

Error   1   Member 'decimal.Round(decimal)' cannot be accessed with an instance     reference; qualify it with a type name instead
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 8

这里的冲突是你的扩展方法和decimal.Round.如已经发现的,这里最简单的解决方法是使用不同的名称.类型的方法总是优先于扩展方法,甚至与static方法冲突.