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

Fra*_*cal 7 f# expression

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

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

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

Fyo*_*kin 11

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

type MyAttribute() = inherit System.Attribute()

[<My>]
let f x = x+1
Run Code Online (Sandbox Code Playgroud)

如您所见,将属性应用于代码单元时可以省略后缀"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
Run Code Online (Sandbox Code Playgroud)

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

[<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
Run Code Online (Sandbox Code Playgroud)

这是一个更详细地解释自定义属性的教程.

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

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