F#属性的typeof和"这不是一个恒定的前pression" [英] F# attributes, typeof, and "This is not a constant expression"

查看:160
本文介绍了F#属性的typeof和"这不是一个恒定的前pression"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:增加了一个更完整的例子,它澄清了问题。

Added a more complete example, which clarified the problem.

一些.NET属性需要键入键入的参数。一个人如何在F#中声明这些参数?

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

例如,在C#中,我们可以做到这一点:

For example, in C# we can do this:

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

不过,在F#以下...

But, in F# the following...

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

...导致一个编译器错误:这不是一个恒定的前pression或有效的自定义属性值

推荐答案

您应该解决的属性类型前锋的使用出台了循环型的依赖。下面的代码片段显示了如何在F#来完成:

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()

这篇关于F#属性的typeof和&QUOT;这不是一个恒定的前pression&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆