Enums 如何在枚举中保留值类型

Enums 如何在枚举中保留值类型,enums,f#,attributes,value-type,Enums,F#,Attributes,Value Type,让我们看一下下面的代码,并假设MyAttribute和test函数都不能更改 type MyAttribute() = inherit Attribute() let mutable prop = null member this.Prop with get(): obj = prop and set(value) = prop <- value type MyEnum = | A = 1 | B = 2

让我们看一下下面的代码,并假设
MyAttribute
test
函数都不能更改

type MyAttribute() =
    inherit Attribute()

    let mutable prop = null

    member this.Prop
        with get(): obj = prop
        and  set(value) = prop <- value


type MyEnum = 
    | A = 1
    | B = 2

[<My(Prop = MyEnum.B)>]
type MyClass = class
    end

let test () =
   let t = typeof<MyClass>
   let a = t.GetCustomAttributes(false).[0] :?> MyAttribute

   let e = a.Prop
   Convert.ToString(e, Globalization.CultureInfo.CurrentCulture)

我猜,我对编译器内部的知识实际上是有限的,但我猜这与类型推断有关。int-Enum之间存在等价性,我怀疑类型推断正在将其减少到可能的最低类型,在本例中为int

open System

type MyAttribute() =
    inherit Attribute()

    let mutable prop = null

    member this.Prop
        with get(): obj = prop
        and  set(value) = prop <- value


type MyEnum = 
    | A = 1
    | B = 2

[<My(Prop = MyEnum.B)>]
type MyClass = class
    end

let test () =
   let t = typeof<MyClass>
   let a = t.GetCustomAttributes(false).[0] :?> MyAttribute

   let e = a.Prop :?> MyEnum //Note
   Convert.ToString(e, Globalization.CultureInfo.CurrentCulture)
开放系统
类型MyAttribute()=
继承属性()
设可变属性=null
请记住这个
使用get():obj=prop
和设置(值)=属性MyAttribute
设e=a.Prop:?>MyEnum//Note
Convert.ToString(e,Globalization.CultureInfo.CurrentCulture)

你能分享你提到的等价的C代码吗?@MarcinJuraszek:edited你在F中调用
GetCustomAttributes()
,在C中调用
false
;不确定这是怎么回事,但至少是有区别的。看起来C#和F#编译枚举(或属性)的方式有区别。如果在C#中定义所有类型,然后在F#中的
test
函数中使用它们,它也会返回枚举案例名称而不是整数值。我造成了一个问题:问题是我无法更改负责读取该属性的代码-它位于另一个不了解我的枚举的库中
open System

type MyAttribute() =
    inherit Attribute()

    let mutable prop = null

    member this.Prop
        with get(): obj = prop
        and  set(value) = prop <- value


type MyEnum = 
    | A = 1
    | B = 2

[<My(Prop = MyEnum.B)>]
type MyClass = class
    end

let test () =
   let t = typeof<MyClass>
   let a = t.GetCustomAttributes(false).[0] :?> MyAttribute

   let e = a.Prop :?> MyEnum //Note
   Convert.ToString(e, Globalization.CultureInfo.CurrentCulture)