我已经多次使用扩展方法,并且没有遇到这个问题。有人知道为什么会抛出错误吗?
/// <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);
}
用法:
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",效果很好。我猜是某种命名冲突……"
没有错误了:
/// <summary>
/// Rounds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="decimals">The decimals.</param>
/// <returns></returns>
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();