繁体   English   中英

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

[英]F# Create custom attribute to expression

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

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

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

要创建自定义属性,只需声明一个继承自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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM