Error with rounding extension on decimal - cannot

2019-06-16 15:46发布

问题:

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