简体   繁体   English

F#中的内插字符串

[英]Interpolated strings in F#

I am trying to use the Entity Framework Core interpolated SQL query function in F# which requires a FormattableString .我正在尝试在需要FormattableString F# 中使用 Entity Framework Core 内插 SQL 查询函数。 However to my surprise it doesn't function as I cannot find a way to convert a regular F# string to that type.然而令我惊讶的是,它不起作用,因为我找不到将常规 F# 字符串转换为该类型的方法。 I figured just doing what you do in C# would work but it doesn't.我想只要做你在 C# 中做的事情就行了,但事实并非如此。 Here is the code I currently have:这是我目前拥有的代码:

let fromDbUser (u : Entity.User) = 
    {
        name = u.Name
        age = u.Age
        phone = u.Phone
    }

let mname = "Foo" 

let ctx = new Entity.DatabaseContext()
ctx.User.FromSqlInterpolated($"Select * FROM User Where name = {mname};") 
|> Seq.map(fromDbUser)
|> printfn "%A"

Running that block of code yields a compile error:运行该代码块会产生编译错误:

This token is reserved for future use此令牌保留供将来使用

I have been trying to google around but I was unable to find any way to get this to work, any help would be most appreciated!我一直在尝试谷歌搜索,但我找不到任何方法来让它工作,任何帮助将不胜感激!

When this was asked, F# didn't have string interpolation.当被问到这一点时,F# 没有字符串插值。

Today though, there is an RFC for it that is merged in in F# 5.0 allowing string interpolation in F#.不过,今天有一个RFC已合并到 F# 5.0 中,允许在 F# 中进行字符串插值。


The error was because the $ symbol is reserved (for 6 years+ as of writing), and will probably be used for string interpolation when it is added.错误是因为$符号是保留的(在撰写本文时已保留6 年以上),并且在添加时可能会用于字符串插值。

As Dave pointed out, interpolation isn't implemented yet.正如 Dave 指出的,插值尚未实现。 But for methods that absolutely require an FormattableString or an IFormattable , you can use FormattableStringFactory.Create但是对于绝对需要FormattableStringIFormattable ,您可以使用FormattableStringFactory.Create

let query (sql: FormattableString)  = 
    printfn "%s" (sql.ToString(null, null))

let mname = "Foo"         
let fstr = FormattableStringFactory.Create("Select * FROM User Where name = {0};", mname)

query fstr

It's available from F# 5.0.它可从 F# 5.0 获得。

> let mname = "Foo" ;;
val mname : string = "Foo"

> let str = $"Select * FROM User Where name = {mname};" ;;
val str : string = "Select * FROM User Where name = Foo;"

Check this out.看一下这个。 https://docs.microsoft.com/en-us/dotnet/fsharp/whats-new/fsharp-50#string-interpolation https://docs.microsoft.com/en-us/dotnet/fsharp/whats-new/fsharp-50#string-interpolation

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

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