简体   繁体   English

无法在 F# 中编写 CLI 兼容的扩展方法

[英]Can't write CLI-Compatible Extension Methods in F#

I have the following F# code which I am attempting to use to write extension methods for C#.我有以下 F# 代码,我试图用它来编写 C# 的扩展方法。 I'm using F# 4.5 on .NET Core 2.2 (macOS), with C# 7.3 attempting to call the extension methods.我在 .NET Core 2.2 (macOS) 上使用 F# 4.5,C# 7.3 尝试调用扩展方法。

open System
open System.Runtime.CompilerServices

[<assembly: Extension>]
do ()

[<Extension>]
module Extensions =
    [<CompiledName("Print"); Extension>]
    type System.String with
        [<Extension>]
        static member inline Print(str : System.String) = Console.WriteLine(str)

    [<CompiledName("Blorp"); Extension>]
        type System.Object with
            [<Extension>]
            static member inline Blorp(o : System.Object) = Console.WriteLine("Blorp")

This is mostly taken from the F# 4.1 specification, with the assembly attribute cribbed from here .这主要取自 F# 4.1 规范,汇编属性取自此处 I'm using JetBrains Rider and the namespace Extensions that it's under is imported properly and the method calls even get highlighted properly in the C# function body where they get called, showing their type.我正在使用 JetBrains Rider 并且它所在的命名空间扩展已正确导入,并且方法调用甚至在调用它们的 C# 函数体中正确突出显示,显示了它们的类型。 But when I do dotnet run, I get a CS1061 build error for both extensions, saying the instances don't contain a definition for either method and no extension methods were found.但是当我运行 dotnet 时,我收到了两个扩展的 CS1061 构建错误,说这些实例不包含任何一种方法的定义,也没有找到扩展方法。 The same methods written in C# and VB.NET work fine.用 C# 和 VB.NET 编写的相同方法工作正常。 What am I doing wrong?我究竟做错了什么? Is it no longer possible to write CLI-compatible extension methods in F#?是否不再可能在 F# 中编写与 CLI 兼容的扩展方法?

@dumetrulo in the comment had the solution here.评论中的@dumetrulo 在这里提供了解决方案。 The extension methods need to be let-bound functions in a module, without the enclosing type declaration:扩展方法需要是模块中的 let-bound 函数,没有封闭的类型声明:

namespace Extensions

open System
open System.Runtime.CompilerServices

[<Extension>]
module Extensions =
    [<Extension>]
    let Print(str : System.String) = Console.WriteLine(str)

    [<Extension>]
    let Blorp(o : System.Object) = Console.WriteLine("Hello World from an F# Extension Method!")

Additionally, the [<assembly: Extension>] attribute appears to be unnecessary此外, [<assembly: Extension>]属性似乎是不必要的

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

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