F#为表达式创建自定义属性

问题描述 投票:6回答:1

在F#中,如何创建自定义属性以应用于表达式?我到处寻找资源,但我一无所获。

例如,属性[<Entrypoint>]可以应用于某个表达式,因此编译器可以推断该表达式应该是array string -> int类型。

如何创建自定义属性以使用simillary?

f# expression
1个回答
11
投票

要创建自定义属性,只需声明一个继承自System.Attribute的类:

type MyAttribute() = inherit System.Attribute()

[<My>]
let f x = x+1

如您所见,将属性应用于代码单元时可以省略后缀“Attribute”。 (可选)您可以提供属性参数或属性:

type MyAttribute( x: string ) =
    inherit System.Attribute()
    member val Y: int = 0 with get, set

[<My("abc", Y=42)>]
let f x = x+1

在运行时,您可以检查类型,方法和其他代码单元,以查看应用于哪些属性,以及检索其数据:

[<My("abc", Y=42)>]
type SomeType = A of string

for a in typeof<SomeType>.GetCustomAttributes( typeof<MyAttribute>, true ) do 
    let my = a :?> MyAttribute
    printfn "My.Y=%d" my.Y

// Output:
> My.Y=42

Here is a tutorial更详细地解释自定义属性。

但是,您无法使用自定义属性来强制执行编译时行为。 EntryPointAttribute很特别 - 也就是说,F#编译器知道它的存在并给予特殊处理。 F#中还有一些其他特殊属性 - 例如,NoComparisonAttributeCompilationRepresentationAttribute等 - 但是你不能告诉编译器对你自己创建的属性给予特殊处理。

如果你描述了你更大的目标(即你想要实现的目标),我相信我们能够找到更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.