简体   繁体   English

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

[英]F# Create custom attribute to expression

In F#, how can I create a custom attribute to apply on expressions? 在F#中,如何创建自定义属性以应用于表达式? I looked for resources everywhere, but I didn't find nothing. 我到处寻找资源,但我一无所获。

For exemple The attribute [<Entrypoint>] can be applied to some expression, and by consequence the compiler can infer that expression should be of type array string -> int . 例如,属性[<Entrypoint>]可以应用于某个表达式,因此编译器可以推断该表达式应该是类型array string -> int

How can I create a custom attribute to work simillary ? 如何创建自定义属性以使用simillary?

To create a custom attribute, simply declare a class that inherits from System.Attribute : 要创建自定义属性,只需声明一个继承自System.Attribute的类:

type MyAttribute() = inherit System.Attribute()

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

As you can see, the suffix "Attribute" can be omitted when applying the attribute to code units. 如您所见,将属性应用于代码单元时可以省略后缀“Attribute”。 Optionally, you can give your attribute parameters or properties: (可选)您可以提供属性参数或属性:

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

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

At runtime, you can inspect types, methods, and other code units to see which attributes are applied to them, and to retrieve their data: 在运行时,您可以检查类型,方法和其他代码单元,以查看应用于哪些属性,以及检索其数据:

[<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 explaining custom attributes in more detail. 这是一个更详细地解释自定义属性的教程

However , you cannot use custom attributes to enforce compile-time behavior. 但是 ,您无法使用自定义属性来强制执行编译时行为。 The EntryPointAttribute is special - that is, the F# compiler knows about its existence and gives it special treatment. EntryPointAttribute特殊的 - 也就是说,F#编译器知道它的存在并给予特殊处理。 There are some other special attributes in F# - for example, NoComparisonAttribute , CompilationRepresentationAttribute , etc., - but you cannot tell the compiler to give special treatment to attributes that you yourself created. F#中还有一些其他特殊属性 - 例如, NoComparisonAttributeCompilationRepresentationAttribute等,但您无法告诉编译器对您自己创建的属性进行特殊处理。

If you describe your larger goal (ie what you're trying to achieve), I'm sure we'll be able to find a better solution. 如果你描述了你更大的目标(即你想要实现的目标),我相信我们能够找到更好的解决方案。

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

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