属性中的F#位置参数

时间:2011-03-16 16:31:43

标签: attributes f#

我正在尝试使用位置参数在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
}

我尝试了几种不同的方法,但这是我最接近的方法。

3 个答案:

答案 0 :(得分:3)

我在您的代码中看到了两个问题

  1. 为了使其正常工作,您需要为ColumnAttribute定义无参数构造函数。
  2. IndexName的类型分别为int optionstring option,但您需要intstring
  3. 尝试以下

    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