3

我在 C# 代码中声明了两个类:

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)
     {
         ...
     }
}

虽然从 C# 调用B.TryParse没有问题,因为正确的重载是由 out 参数类型决定的,应该提前声明。由于 out 参数是 F# 中结果的一部分的转换,我们得到了两个具有相同参数签名的函数......并且从 F# 调用会导致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.错误。我理解这个问题,甚至会声明TryParsenew......如果它不是静态的。

消息本身并不是很有帮助:绝对不清楚要添加哪种注释以及在哪里添加。

我该怎么打这个电话?最愚蠢的想法是重命名函数之一,但可能有更聪明的方法?

4

2 回答 2

4

您需要为传递给 try 方法的变量添加类型注释,在本例中是 out 变量,因为这是发生变化的东西。我认为这样的事情应该有效:

let res, (b:B) = B.TryParse "MyString"

在 F# 中,类型注释位于标识符之后,并以冒号 (:) 开头。

(注意:在 F# 中,输出参数可以从结果中恢复为元组)

于 2012-05-24T13:55:00.073 回答
3

有几种方法可以解决这个问题:

  • 添加显式类型注释(如 Robert 建议的那样)。
  • 使用保存从 out 参数返回的值的变量作为稍后函数调用的参数,其中函数的参数“已知”为“B”类型;如果函数的参数显式声明为类型“B”(通过添加显式类型注释),这通常效果最好。
  • Create a inline helper function which uses statically-resolved generics to invoke the TryParse method of whatever object it's passed.
于 2012-05-24T14:01:06.717 回答