简体   繁体   English

我如何得到警告 FS1125(通用类型“xxx”的实例化丢失并且无法从...推断)消失?

[英]How do I get warning FS1125 (The instantiation of the generic type 'xxx' is missing and can't be inferred from...) to go away?

The advice from Don Syme doesn't seem to apply in this case. Don Syme 的建议似乎不适用于这种情况。

type WrappedFunction<'a,'b> = 
    private {
        Function:'a -> 'b
    }
    static member Make (f:'a -> int) = {Function = f}
    static member Make (f:'a -> string) = {Function = f}

when used as in当用作

let a = WrappedFunction.Make (fun (a:DateTime) -> a.ToString())

results in the warning.导致警告。

The missing bit of insight here is this: there is no rule to say that the Make static methods have to return the same type on which they are defined.这里缺少的一点洞察力是:没有规则说Make静态方法必须返回定义它们的相同类型。

Check this out:看一下这个:

let w : WrappedFunction<int,int> = WrappedFunction<int,bool>.Make (fun i -> string i)

This works, even though I call the Make function on WrappedFunction<int,bool> , but the result has type WrappedFunction<int,int> .这有效,即使我在WrappedFunction<int,bool>上调用Make函数,但结果的类型为WrappedFunction<int,int>

The second type parameter 'b is not mentioned anywhere in the signature of Make , so it doesn't have to match anything.Make任何地方都没有提到第二个类型参数'b ,所以它不必匹配任何东西。 But it still has to be known somehow, so it needs to be specified explicitly.但是它仍然必须以某种方式知道,因此需要明确指定。 And if you don't specify it explicitly, you get the warning.如果您没有明确指定它,则会收到警告。

With the first type parameter 'a it's a different story: since it's mentioned in the signature of Make , it has to match the surrounding type.对于第一个类型参数'a就不同了:因为它在Make的签名中提到过,所以它必须匹配周围的类型。 So, for example, this doesn't work:因此,例如,这不起作用:

let w = WrappedFunction<string, bool>.Make (fun i -> i + 42)
                                                     ^^^^^^
                                                        |
                       "The type 'int' does not match the type 'string'"

If you want the Make methods to "just work" without specifying the type parameters, the usual pattern here is to create a second type with the same name, but without type parameters, and put the methods in it:如果您希望Make方法在不指定类型参数的情况下“正常工作”,这里的常用模式是创建具有相同名称但没有类型参数的第二个类型,并将方法放入其中:

type WrappedFunction<'a,'b> = 
    {
        Function:'a -> 'b
    }

type WrappedFunction =
    static member public Make (f:'a -> int) = {Function = f}
    static member public Make (f:'a -> string) = {Function = f}

But of course, if that case you can't have access to the private constructor.但是当然,如​​果这种情况下您无法访问私有构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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