F# 为表达式创建自定义属性 [英] F# Create custom attribute to expression

查看:21
本文介绍了F# 为表达式创建自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In F#, how can I create a custom attribute to apply on expressions? I looked for resources everywhere, but I didn't find nothing.

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

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.

如何创建自定义属性以进行类似的工作?

How can I create a custom attribute to work simillary ?

推荐答案

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

To create a custom attribute, simply declare a class that inherits from 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. 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.

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

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. 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.

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

If you describe your larger goal (i.e. what you're trying to achieve), I'm sure we'll be able to find a better solution.

这篇关于F# 为表达式创建自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆