F#中枚举的注释

时间:2016-07-02 16:48:45

标签: enums f#

我在F#中有一个枚举:

type Gender = Undisclosed = 0 | Male = 1 | Female = 2

等效的C#代码是

public enum Gender
{
    Undisclosed,
    Male,
    Female
}

事实上,在C#中,我可以更好一步。要在cshtml页面的下拉列表中使用性别,我可以这样做:

public enum Gender
{
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderUndisclosed")] Undisclosed,
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderMale")] Male,
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderFemale")] Female
}

不幸的是,F#编译器说这里不允许"属性"如果我尝试向F#enum成员添加类似的注释。有没有解决的办法?如果可能的话,我想避免创建一个重复的类并执行Automapper voodoo。

2 个答案:

答案 0 :(得分:7)

在属性之前需要|

// Doesn't compile. "Attributes are not allowed here"
type Foo = [<Bar>] Baz = 0

// Compiles.
type Foo = | [<Bar>] Baz = 0

在你的情况下,这将出现:

type Gender = 
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderUndisclosed")>] Undisclosed = 0
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderMale")>] Male = 1
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderFemale")>] Female = 2

答案 1 :(得分:5)

这应该有效:

type Gender = 
    | [<Display>] Undisclosed = 0 
    | [<Display>] Male        = 1 
    | [<Display>] Female      = 2