gpt4 book ai didi

c# - 在 OOP 方法重载中使用 float 会出错

转载 作者:行者123 更新时间:2023-11-30 22:20:34 25 4
gpt4 key购买 nike

如果我这样做,

public class test
{
public int add(int a, float b)
{
return a + Convert.ToInt32(b);
}

public int add(float a, int b)
{
return Convert.ToInt32(a) + b;
}
}

然后它编译成功但给出了后期绑定(bind)运行时错误:

The call is ambiguous between the following methods or properties

但如果我这样做

public class test
{
public int add(int a, float b)
{
return a + Convert.ToInt32(b);
}

public int add(int a, int b)
{
return Convert.ToInt32(a) + b;
}
}

然后它正常工作并在 test.add(1,2) 的情况下调用第二个 add 方法。它也适用于我用小数替换 float 的情况。

我能对上述错误做些解释吗?

最佳答案

因为 int 可以隐式转换为 float,所以编译器不知道是选择将第一个参数转换为 float 还是将第二个参数转换为 float。它们都同样值得转化。

在您的调用站点,通过调用一个 float 和一个整数而不是两个整数来消除歧义:

test t  = new test();
t.add(1.0f, 2);
t.add(1, 2.0f);

关于c# - 在 OOP 方法重载中使用 float 会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com