鸭打字类型增强 [英] Duck Typing & Type Augmenttaion

查看:120
本文介绍了鸭打字类型增强的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我刚刚注意到在使用鸭子类型和类型增强时的奇怪行为.这是代码:

I have just noticed a strange behavior when using duck typing and type augmentation. Here is the code:

命名空间测试
 模块M1 =

   类型System.Double with
      静态成员doit(v:double)= v


    let inline duck(v:^ a)=(^ a:(static member doit:^ a-> ^ a)(v))

    let(v:System.Double)= 2.8

    System.Double.doit(v)  //好的
    
   //类型检查器抱怨
   鸭v

 模块M2 =

   类型A = CA
      与
        静态成员doit(v:A)= v 

   类型B = CB

    //都可以
    M1.duck CA
    A.doit CA       

 模块M3 =

   类型M2.B
      与
        静态成员doit(v:M2.B)= v 
    
    //类型检查器抱怨
    M1.duck M2.CB
    M2.B.doit(M2.CB)  //好的

namespace Test
 module M1 =

    type System.Double with
        static member doit (v:double) = v


    let inline duck (v : ^a) = (^a : (static member doit: ^a -> ^a) (v))

    let (v:System.Double) = 2.8

    System.Double.doit(v)  // ok
    
   // type checker complains
    duck v

 module M2 =

    type A = CA
        with
          static member doit (v:A) = v  

    type B = CB

    // Both ok
    M1.duck CA
    A.doit CA        

 module M3 =

    type M2.B
        with
          static member doit (v:M2.B) = v  
    
    // type checker complains
    M1.duck M2.CB
    M2.B.doit (M2.CB)  // ok

有人对此行为有解释吗?

Has anyone an explanation to this behavior?

谢谢

致谢

让·克里斯托夫(Jean-Christophe)

Jean-Christophe

推荐答案

静态成员约束仅在所使用的类型上具有相应的实际.NET成员时才有效.但是,扩展方法会导致另一种类型的静态方法(即使您像在原始类型上定义的那样调用它们), 因此它们不能与静态成员约束一起使用.在您的示例中,System.Double和M2.B并没有真正的"doit"功能.方法,因此静态需要"doit"方法的方法.这些类型的方法无效.

Static member constraints only work when there are corresponding real .NET members on the type being used.  However, extension methods result in static methods on another type (even though you call them as if they were defined on the original type), so they can't be used with static member constraints.  In your examples, System.Double and M2.B don't really have "doit" methods so methods that statically require a "doit" method on those types won't work.


这篇关于鸭打字类型增强的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆