【问题标题】:Trying to remove ambiguous call in constructor involving int and long试图删除涉及 int 和 long 的构造函数中的模棱两可的调用
【发布时间】:2015-02-19 23:32:30
【问题描述】:

"以下方法或属性之间的调用不明确:'fInt.fInt(int, bool)' 和 'fInt.fInt(long, bool)'"

这是我的两个构造函数:

public fInt(int i, bool scale = true)
{
    if (scale) value = i * SCALE;
    else value = i;
}

public fInt(long i, bool scale = true)
{
    if (scale)
    {
        if(i > long.MaxValue / SCALE || i < long.MinValue / SCALE) 
            Debug.LogError("fInt Overflow on creation with scaling");

        value = i * SCALE;
    }
    else value = i;
}

以下是我使用隐式转换调用 int 的方法:

fInt i = 8;

我希望能够同时使用 int 和 long,这样我就可以避免在不需要时进行额外检查。关于如何解决这个问题的任何想法?我是否只需要这样做:

fInt i = (int)8;
fInt i2 = (long)9;

如果可以避免的话,我宁愿不用额外输入。这是我的隐式转换:

//implicit int to fInt
public static implicit operator fInt(int i)
{
    return new fInt(i);
}

//implicit long to fInt
public static implicit operator fInt(long i)
{
    return new fInt(i);
}

【问题讨论】:

  • 您引用了编译器错误,但除非我忽略它,否则您没有指出编译器所指的代码行。你能做到吗?
  • 您没有发布任何代码,至少在 VS2013 中,会产生您描述的错误。请更具体地说明您的确切问题。
  • @phoog 错误在隐式转换中。 “return new fInt(i);”这一行...它特别源于以下列方式调用构造函数:“new fInt(123);”。我正在将 Mono 与 Unity3D 一起使用……也许这与它有关。
  • @PeterDuniho 它在 Mono 中为我生成错误。我将它与 Unity3D 一起使用
  • @GrantWinney 它似乎在 Visual Studio 中工作正常。 123 应被视为 int 而 123L 应被视为 long。

标签: c# constructor implicit-conversion ambiguity ambiguous


【解决方案1】:

这似乎是 Unity3D 编辑器中的一个错误...因为代码在 Visual Studio 中运行良好。只有在第二个参数是可选的时候才会混淆签名。

【讨论】:

  • 需要可选参数才能导致错误发生? IE。处理没有默认参数值的方法没有歧义错误?也许您应该尝试以旧式方式实现可选参数。 IE。声明更多重载:fInt(int i)fInt(int i, bool scale)fInt(long i)fInt(long i, bool scale)。没有bool参数的两个重载当然只是调用它们对应的重载,传递默认值。
  • 这应该更像是一个 Mono C# 编译器问题,它无法以 Microsoft C# 编译器的方式处理数字。所以说它是 Unity 编辑器的 bug 并不是 100% 正确的。
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
相关资源
最近更新 更多