Error with rounding extension on decimal - cannot be accessed with an instance reference; qualify it with a type name instead

*爱你&永不变心* 提交于 2019-12-10 12:55:50

问题


I've used extension methods numerous times, and haven't run into this issue. Anyone have any ideas why this is throwing an error?

 /// <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);
 }

Usage:

decimal newAmount = decimal.Parse("3.33333333333434343434");
this.rtbAmount.Text = newAmount.Round(3).ToString();

newAmount.Round(3) is throwing the compiler error:

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

回答1:


The conflict here is a conflict between your extension method and decimal.Round. The simplest fix here, as already discovered, is to use a different name. Methods on the type always take precedence over extension methods, even to the point of conflicting with static methods.




回答2:


Sorry for answering my own question so fast. Within a second of posting this, it dawned on me that perhaps the compiler didn't like "Round" as the name. So I changed it to "RoundNew" and it worked. Some sort of naming conflict I guess...'

No errors anymore:

/// <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();


来源:https://stackoverflow.com/questions/7044520/error-with-rounding-extension-on-decimal-cannot-be-accessed-with-an-instance-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!