简体   繁体   English

从C#调用F#`printfn`

[英]Call F# `printfn` from C#

How can I call F# printfn directly from C# code? 如何直接从C#代码调用F# printfn I see there's a 我看到有一个

T PrintfModule.PrintFormat<T>(PrintfFormat<T, TextWriter, Unit,Unit> format)

For example, I have F# assembly that defines x : 例如,我有定义x F#程序集:

type R = { r: R }
let rec x = { r = x }

In another C# assembly, how can I print x by calling code that is equivalent to printfn "%A" x with PrintfModule.PrintFormatLine ? 在另一个C#组件,我怎么能打印x通过调用代码,相当于printfn "%A" xPrintfModule.PrintFormatLine

A shorter version of AlexAtNet's anwser is: AlexAtNet的答案的简短版本是:

PrintfModule
    .PrintFormatLine(
        new PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit, Program.R>("%A"))
    .Invoke(Program.x);

Although I don't understand why there's a need of casting (PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit>) . 尽管我不明白为什么需要强制转换(PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit>) If someone knows the reason please teach me. 如果有人知道原因,请教我。

I've created F# file Program.fs: 我创建了F#文件Program.fs:

open System

type R = { r: R }
let rec x = { r = x }

[<EntryPoint>]
let main argv =
    printfn "%A" x
    0

compiled it and then decompiled to C#: 编译它,然后反编译为C#:

using Microsoft.FSharp.Core;
...

public static Program.R x {
    get { return \u0024Program.x\u00406; }
}

[EntryPoint]
public static int main(string[] argv)
{
    \u0024Program.init\u0040 = 0;
    int init = \u0024Program.init\u0040;
    ExtraTopLevelOperators
      .PrintFormatLine<FSharpFunc<Program.R, Unit>>(
          (PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit>)
          new PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit, Program.R>("%A")).Invoke(Program.x);
    return 0;
}

public sealed class R : IEquatable<Program.R>, IStructuralEquatable, IComparable<Program.R>, IComparable, IStructuralComparable
{
    internal Program.R r\u0040;
    public Program.R r { get { return this.r\u0040; } }
    public R(Program.R r) { this.r\u0040 = r; }
}

Hope it will give you a hint how to do that. 希望它会提示您如何操作。

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

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