【问题标题】:Error with rounding extension on decimal - cannot be accessed with an instance reference; qualify it with a type name instead十进制舍入扩展错误 - 无法通过实例引用访问;改为使用类型名称来限定它
【发布时间】:2011-09-07 08:31:38
【问题描述】:

我用过很多次扩展方法,都没有遇到过这个问题。有人知道为什么会引发错误吗?

 /// <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

【问题讨论】:

    标签: c# .net visual-studio-2010 extension-methods rounding


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

    很抱歉这么快就回答了我自己的问题。在发布此消息的一秒钟内,我突然意识到编译器可能不喜欢“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();
    

    【讨论】:

    • 是否有可能将扩展方法命名为“Round”与 Math.Round 方法发生冲突?这似乎更像是编译器的错误,而不是真正的错误。
    • 冲突是十进制的。Round: msdn.microsoft.com/en-us/library/k4e2bye2.aspx - 这不是编译器错误
    • 哦,我完全忽略了这一点。请发布答案,以便我给你信用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多