F# attributes, typeof, and “This is not a constant expression”

北慕城南 提交于 2019-12-13 13:13:03

问题


EDIT: Added a more complete example, which clarified the problem.

Some .NET attributes require a parameter of type Type. How does one declare these parameters in F#?

For example, in C# we can do this:

[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Truck))]
class Vehicle { }
class Car : Vehicle { }
class Truck : Vehicle { }

But, in F# the following...

[<XmlInclude(typeof<Car>)>]
[<XmlInclude(typeof<Truck>)>]
type Vehicle() = class end
type Car() = inherit Vehicle()
type Truck() = inherit Car()

...results in a compiler error: This is not a constant expression or valid custom attribute value.


回答1:


You should address a circular type dependency introduced by forward usage of types in attributes. The snippet below shows how this can be done in F#:

// Compiles OK
[<AttributeUsage(AttributeTargets.All, AllowMultiple=true)>]
type XmlInclude(t:System.Type) =
   inherit System.Attribute()

[<XmlInclude(typeof<Car>)>]
[<XmlInclude(typeof<Truck>)>]
type Vehicle() = class end
and Car() = inherit Vehicle()
and Truck() = inherit Car()



回答2:


Can you try putting together a more complete example that gives the error? I just quickly tried something similar and it works fine (in F# 3.0 in Visual Studio 2012):

type Car = C

type XmlInclude(typ:System.Type) =
  inherit System.Attribute()

[<XmlInclude(typeof<Car>)>]
let foo = 0

I guess there is some tiny detail somewhere that confuses the F# compiler for some reason - but it should understand typeof (which is, in reality, a function) and allow its use in attributes.



来源:https://stackoverflow.com/questions/18369922/f-attributes-typeof-and-this-is-not-a-constant-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!