问题
I have two classes declared in C# code:
public class A
{
public static bool TryParse(string value, out A result)
{
...
}
}
public class B : A
{
public static bool TryParse(string value, out B result)
{
...
}
}
While calling B.TryParse
from C# isn't problem, because correct overload is determined by out parameter type, which should be declared in advance. As out parameter is transformet to part of result in F#, we got two function with same parameter signature... And call from F# causes A unique overload for method 'TryParse' could not be determined based on type information prior to this program point. A type annotation may be needed.
error. I understand the issue, and would even declare TryParse
as new
... If it weren't static.
The message itself is not very helpful: it's absolutely not cleare what kind of annotation and where to add.
How can I do this call? Most stupid idea is to rename one of functions, but may be there are more clever way?
回答1:
You need to add a type annotation to the variables you are passing to the try method, in this case the out variable as this is the thing that changes. I think something like this should work:
let res, (b:B) = B.TryParse "MyString"
In F# type annotations come after the an identifier and are preceded by a colon (:).
(Note: in F# out parameters can be recovered as tuple from the result)
回答2:
There are a few ways to solve the problem:
- Add an explicit type annotation (as Robert suggested).
- Use the variable which holds the value returned from the out parameter as an argument to some later function call where the function's parameter is "known" to be of type 'B'; this usually works best if the function's parameter is explicitly declared as type 'B' (by adding an explicit type annotation).
- Create a inline helper function which uses statically-resolved generics to invoke the TryParse method of whatever object it's passed.
来源:https://stackoverflow.com/questions/10738507/f-how-to-specify-static-overload-to-use