编辑:添加了一个更完整的示例,澄清了问题.
某些.NET属性需要类型参数Type
.如何在F#中声明这些参数?
例如,在C#中我们可以这样做:
[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Truck))]
class Vehicle { }
class Car : Vehicle { }
class Truck : Vehicle { }
Run Code Online (Sandbox Code Playgroud)
但是,在F#中,以下......
[<XmlInclude(typeof<Car>)>]
[<XmlInclude(typeof<Truck>)>]
type Vehicle() = class end
type Car() = inherit Vehicle()
type Truck() = inherit Car()
Run Code Online (Sandbox Code Playgroud)
...导致编译器错误:这不是常量表达式或有效的自定义属性值.
您应该解决由属性中的类型的前向使用引入的循环类型依赖性.下面的代码段显示了如何在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()
Run Code Online (Sandbox Code Playgroud)