我正在尝试使用位置参数在F#中创建一个属性,但始终失败。
type ColumnAttribute(?index:int,?name:string) =
inherit Attribute()
let mutable index = index
let mutable name = name
member x.Index
with get() = index
and set value = index <- value
member x.Name
with get() = name
and set value = name <- value
type Substance = {
[<Column(Index=1)>] Name : string
[<Column(Index=0)>] Id : int
[<Column(Name="sequence")>] Sequence : string
}
我尝试了几种不同的方法,但这是我最接近的方法。
答案 0 :(得分:3)
我在您的代码中看到了两个问题
ColumnAttribute
定义无参数构造函数。Index
和Name
的类型分别为int option
和string option
,但您需要int
和string
。尝试以下
type ColumnAttribute(index:int option,name:string option) =
inherit Attribute()
let mutable index = index
let mutable name = name
new () = ColumnAttribute (None, None)
member x.Index
with get() = match index with | Some i -> i | None -> 0
and set value = index <- Some value
member x.Name
with get() = match name with | Some n -> n | None -> ""
and set value = name <- Some value
type Substance = {
[<Column(Index=1)>] Name : string
[<Column(Index=0)>] Id : int
[<Column(Name="sequence")>] Sequence : string }
答案 1 :(得分:2)
这有效:
type ColumnAttribute() =
inherit System.Attribute()
let mutable index = 0
let mutable name = ""
member x.Index
with get() = index
and set value = index <- value
member x.Name
with get() = name
and set value = name <- value
type Substance = {
[<Column(Index=1)>] Name : string
[<Column(Index=0)>] Id : int
[<Column(Name="sequence")>] Sequence : string
}
属性已经支持类似于命名参数的属性设置器语法。为了得到你想要的东西,使用无参数构造函数并依赖于属性语法,而不是命名参数(无论如何它都不适用于属性,因为它们被推断为option
... ... t有资格作为常数表达式)。
答案 2 :(得分:0)
你走了:
open System
type ColumnAttribute() =
inherit Attribute()
let mutable index = 0
let mutable name = ""
member x.Index
with get() = index
and set value = index <- value
member x.Name
with get() = name
and set value = name <- value
type Substance = {
[<Column(Index=1)>] Name : string
[<Column(Index=0)>] Id : int
[<Column(Name="sequence")>] Sequence : string
}
请注意,原始尝试中的可选参数(例如?index
)导致类型为例如int option
而不是int
。