F#:使用类型定义引用吗? [英] F#: Quotation with type definition?
问题描述
我正在使用引号,但看不到类型定义的表达模式.真的没有人吗,还是我错过了什么?
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屋!