为什么"代码不够通用"?

Joh*_*bom 12 generics f# type-inference inline

任何人都可以解释为什么下面的第二个例子不会编译?

'测试2'给出了"错误FS0670:这个代码不够通用.类型变量^ a不能一概而论,因为它会逃避它的范围." 我无法理解此错误消息.

// Test 1
type test1<'a> = | A of 'a 
  with
    override t.ToString() = 
      match t with
      | A a -> a.ToString()

// Test 2
type test2<'a> = | A of 'a 
  with
    override t.ToString() = 
      match t with
      | A a -> string a

// Test 3
type test3<'a> = | A of 'a 
  with
    override t.ToString() = 
      match t with
      | A a -> string (a :> obj)
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 5

这是另一个复制品:

let inline f< ^T>(x:^T) = box x

type test4<'a> = | A of 'a  
  with 
    member t.M() =  
        match t with
        | A a -> f a
Run Code Online (Sandbox Code Playgroud)

string是一个使用静态类型约束的内联函数,这些函数的错误诊断有时很差.我真的不了解诊断消息本身,但重点是,在呼叫站点,我们不知道泛型类型'a,这意味着我们无法内联正确的调用版本string(或f在我的repro中) .例如,在你向上转换的情况下obj,我们知道我们想要内联obj版本string,所以没关系.