F#:使用类型定义引用吗? [英] F#: Quotation with type definition?

查看:73
本文介绍了F#:使用类型定义引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 @@>

给出引号文字中意外的关键字'type'."

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

推荐答案

您不能.您只能引用代码,也就是说,任何

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.

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

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

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

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

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

例如,此示例代码显示MyType的所有反映的定义成员的AST:

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 _ -> ()
()

这篇关于F#:使用类型定义引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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