让我们看下面的代码片段,并假设既不能更改 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)
false
,在 C# 中使用true
调用了GetCustomAttributes()
方法;不确定这样做的作用是什么,但至少有所区别。 - TeaDrivenDevtest
函数中使用它们,它也会返回枚举案例名称而不是整数值。 - TeaDrivenDev