F#: how to specify static overload to use?

久未见 提交于 2019-12-12 14:42:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!