F#:带有类型定义的引用?

发布于 2024-09-12 00:25:22 字数 171 浏览 2 评论 0原文

我正在使用引号,但看不到类型定义的表达式模式。真的没有吗,还是我错过了什么?

<@@ type MyType (name:string) =
    member x.Name = name @@>

给出“引号文字中出现意外的关键字‘type’。”

I'm playing around with quotations and I can't see an expression pattern for type definitions. Is there really not one, or am I missing something?

<@@ type MyType (name:string) =
    member x.Name = name @@>

Gives "Unexpected keyword 'type' in quotation literal."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅气称霸 2024-09-19 00:25:22

你不能。您只能引用代码,也就是说,任何 有效的 F# 表达式。类型定义不被视为代码,而是定义。

您可能想要做的是将 ReflectedDefinition 属性放在类型成员上:

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

如果您想检索具有 ReflectedDefinition 的成员的 AST,您可以使用 Expr.TryGetReflectedDefinition 函数。

例如,此示例代码打印 MyType 的所有反射定义成员的 AST:

open Microsoft.FSharp.Quotations
open System.Reflection

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

let mis = typeof<MyType>.GetMembers()
for mi in mis do
    try
        match Expr.TryGetReflectedDefinition(mi :?> MethodBase) with
        | Some(e) ->  printfn "%A" e
        | None    -> ()
    with _ -> ()
()

You can't. You can only quote code, that is to say, any valid F# expression. Type definitions are not considered as code, but definitions.

What you might want to do is put ReflectedDefinition attribute on a type members:

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

If you want to retrieve the AST of members that have ReflectedDefinition you can use Expr.TryGetReflectedDefinition function.

E.g, this sample code prints ASTs of all reflected definition members of MyType:

open Microsoft.FSharp.Quotations
open System.Reflection

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

let mis = typeof<MyType>.GetMembers()
for mi in mis do
    try
        match Expr.TryGetReflectedDefinition(mi :?> MethodBase) with
        | Some(e) ->  printfn "%A" e
        | None    -> ()
    with _ -> ()
()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文