F#中枚举的注释

Rob*_*don 7 enums f#

我在F#中有一个枚举:

type Gender = Undisclosed = 0 | Male = 1 | Female = 2
Run Code Online (Sandbox Code Playgroud)

等效的C#代码

public enum Gender
{
    Undisclosed,
    Male,
    Female
}
Run Code Online (Sandbox Code Playgroud)

事实上,在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
}
Run Code Online (Sandbox Code Playgroud)

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

31e*_*384 7

你需要一个|属性之前.

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

// Compiles.
type Foo = | [<Bar>] Baz = 0
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)


kro*_*nis 5

这应该工作:

type Gender = 
    | [<Display>] Undisclosed = 0 
    | [<Display>] Male        = 1 
    | [<Display>] Female      = 2
Run Code Online (Sandbox Code Playgroud)