我试图建立一个属性来验证类型的某个实例。
为此,我必须将强制ObjectInstance
转换为该类型。
我需要在该类型的成员上设置属性。
因此,我们需要and
在循环定义中使用关键字。
但是在以下情况下,我得到的错误是
自定义属性必须调用对象构造函数
在下面标记的行上。
namespace Test
open System
open System.ComponentModel.DataAnnotations
[<AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)>]
type MyAttribute() =
class
inherit ValidationAttribute ()
override this.IsValid (value: Object, validationContext: ValidationContext) =
match validationContext.ObjectInstance with
| :? MyClass as item ->
// TODO more validation
ValidationResult.Success
| _ ->
new ValidationResult("No no no")
end
and MyClass(someValue) =
[<Required>]
[<Range(1, 7)>]
//vvvvvvvvvvvvvvv
[<MyAttribute>]
//^^^^^^^^^^^^^^^
member this.SomeValue : int = someValue
我尝试手动调用构造函数,例如:
[<MyAttribute()>]
// or
[<new MyAttribute()>]
但是它们都不被系统接受。
F#专家可以在这里帮助我吗?
一种解决方案是首先在签名文件中描述您的类型。
由于该属性是在签名文件中指定的,因此您无需在实现文件中再次添加该属性:
Foo.fsi:
namespace Foo
open System
[<AttributeUsage(AttributeTargets.Property)>]
type MyAttribute =
inherit System.Attribute
new : unit -> MyAttribute
member Foo : unit -> MyClass
and MyClass =
new : someValue : int -> MyClass
[<MyAttribute()>]
member SomeValue : int
Foo.fs:
namespace Foo
open System
[<AttributeUsage(AttributeTargets.Property)>]
type MyAttribute() =
inherit Attribute()
member this.Foo () =
new MyClass(1)
and MyClass(someValue) =
// [<MyAttribute()>] -> specified in the fsi, still appears in compiled code
member this.SomeValue : int = someValue
请参阅https://msdn.microsoft.com/en-us/library/dd233196.aspx以获取参考
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句