f# - 循环引用和构造函数

标签 f# circular-dependency circular-reference

我试图建立一个属性来验证类型的某个实例。

为此,我必须将ObjectInstance强制转换为该类型。

我需要在该类型的成员上设置属性。

因此,对于循环定义,我们需要诉诸and关键字。

但是在以下情况下,我得到的错误是

A custom attribute must invoke an object constructor



在下面标记的行上。
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以供引用

关于f# - 循环引用和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36598363/

相关文章:

list - 递归处理列表和列表的子列表给出类型不匹配

F# BinarySearch 返回位置

java - 如何对这两个耦合类应用解耦

javascript - 全局对象/范围和未定义的循环引用

c++ - 是否有任何静态分析工具可以帮助检测 shared_ptr<> 循环引用?

c# - F# 中的记录实例在 C# 中为空

f# - 如何对 F# Map 集合中的值求和

C++ 使用类 A 作为类 B 的成员函数的参数,类 B 是类 A 的成员

google-sheets - Google 电子表格循环依赖

c# - 序列化代码示例中的无限循环