让我们看下面的代码,并假定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)
我希望
test
返回B
但它返回2。生成的IL代码显示有关枚举类型的信息丢失,并且传递给属性的值仅为2。有什么办法(我想应该是某种属性)来保留属性值中的类型? C#中更有趣的等效代码可以按预期工作
等效的C#:
class MyAttribute : Attribute
{
public object A { get; set; }
}
enum T { A,B,C }
[My(A = T.A)]
class MyClass
{ }
var a = typeof(MyClass).GetCustomAttributes(false)[0] as MyAttribute;
Convert.ToString(a.A, System.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)
关于enums - 如何在枚举中保留值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732830/