简体   繁体   中英

Ambiguous call error, both functions have different return types

I have two overloaded methods, both called FunctionX. One of them returns a Boolean object, and one a predefined class called Logs.

The error I'm getting is: The call is ambiguous between the following methods or properties: 'FunctionX(string)' and 'FunctionX(string)'.

In one of my other methods, I call FunctionX(string), expecting the Log object, but it's throwing this error. I thought the compiler was supposed to look at the return type and figure this out for itself. How can I fix this?

You cannot have more then one function using the same signature eg

string Function1(bool t)
int Function1(bool t)

You need to call each function different names, or having different params eg

string Function1(bool t)
int Function1(bool t, int g)

You can't overload a method to have different return types. How would the compiler know what to call here?

string Foo() { /* ... */ }
int Foo() { /* ... */ }

object f = Foo();

Language designers need to take all circumstances into account, not only those that are most trivial.

There is no way for the compiler to distinguish between functions with the same method signature except for the return type. And as far as I know no compiler can that is strongly typed. You must change the signature in some way. On option is to use a generic function and provide the return type.

While languages like Perl and Haskell do support overloading by return type, function overloading by return type is not supported by most statically typed languages. So, it is better if you do not make this trivial problem a part of your code.

Added :

You can find more answers in an earlier Stackoverflow discussion here:

Function overloading by return type?

The return type does not partecipating on overloading in C#.

You can, for example:

  1. Declare separate functions FunctionXToLog and FunctionXToBool
  2. FunctionX(string s, out Log logobject) , FunctionX(string s, out bool value)

Just to give you a hint.

您不能拥有两个具有相同签名的函数,只是返回值不同!

The signature of a method is its name and the types of its parameters - only. Its return type is not part of its signature.

Hence the problem you are having, since the two methods have identical signatures. The compiler does not use the return type, or the type of the object being assigned to, to determine which method to call.

You will have to specify the classname of the method you want (assuming that the two methods are in different classes). Or you will have to provide another parameter for one of the methods, to give it a different signature. Or, finally, you will have to rename one of the methods to make them unambiguous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM