作者:手机用户2502926947 | 来源:互联网 | 2023-01-31 04:42
在F#中,如何创建自定义属性以应用于表达式?我到处寻找资源,但我一无所获.
例如,该属性[]
可以应用于某个表达式,因此编译器可以推断该表达式应该是类型array string -> int
.
如何创建自定义属性以使用simillary?
1> Fyodor Soiki..:
要创建自定义属性,只需声明一个继承自的类System.Attribute
:
type MyAttribute() = inherit System.Attribute()
[]
let f x = x+1
如您所见,将属性应用于代码单元时可以省略后缀"Attribute".(可选)您可以提供属性参数或属性:
type MyAttribute( x: string ) =
inherit System.Attribute()
member val Y: int = 0 with get, set
[]
let f x = x+1
在运行时,您可以检查类型,方法和其他代码单元,以查看应用于哪些属性,以及检索其数据:
[]
type SomeType = A of string
for a in typeof.GetCustomAttributes( typeof, true ) do
let my = a :?> MyAttribute
printfn "My.Y=%d" my.Y
// Output:
> My.Y=42
这是一个更详细地解释自定义属性的教程.
但是,您无法使用自定义属性来强制执行编译时行为.这EntryPointAttribute
是特殊的 - 也就是说,F#编译器知道它的存在并给予特殊处理.有F#中其他一些特殊的属性-例如NoComparisonAttribute
,CompilationRepresentationAttribute
等等, -但你不能告诉编译器给予特殊的待遇,你自己创建的属性.
如果你描述了你更大的目标(即你想要实现的目标),我相信我们能够找到更好的解决方案.