类型x的可访问性小于值 [英] Type x is less accessible than the value

查看:47
本文介绍了类型x的可访问性小于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的抽象部分:

Here's an abstraction of my code:

module RootModule

module private SubModule = // I want everything in this module to be inaccessible from outside the file
    let getLength s = String.Length s
    type MyType (s: string) =
        let _str = s
        member this.GetStringLength = getLength _str // for sake of simplicity, a bogus method

let myExternalValue = new SubModule.MyType("Hello")

我收到错误Type 'MyType' is less accessible than the value, member, or type: 'val myExternalValue: SubModule.MyType' it is used in

为什么我不能像这样的私有类实例具有公共访问器?请注意,我在其他文件中一起使用RootModule,只希望在其他文件中可见myExternalValue

Why can't I have public accessors to a private class instance like this? Note that I'm using the RootModule in a different file alltogether, and only wish to have myExternalValue be visible in the other file

推荐答案

您已经隐藏了MyType,但是myExternalValue需要告诉调用者返回的是哪种类型

You have hidden MyType, but myExternalValue need to tell the caller what type is return

有两种方法可以做到这一点:

there are two way to do this:

选项1:返回一个对象,并使用反射来获取值或调用函数

option 1: return an object, and use reflection to get value or to invoke function

module RootModule

open System.Reflection

module private SubModule =
    let getLength s = String.length s

    type MyType (s: string) =
        let _str = s
        member this.GetStringLength with get() = getLength _str

let (?) obj property =
    let flags = BindingFlags.NonPublic ||| BindingFlags.Instance
    obj.GetType().GetProperty(property, flags).GetValue(obj) |> unbox

let myExternalValue = SubModule.MyType("Hello") :> obj

用法:

open RootModule
printfn "%d" <| RootModule.myExternalValue?GetStringLength

选项2:公开行为,但隐藏真实类型

option 2: exposing behavior, but hiding the real type

module RootModule

type RootType =
    abstract member GetStringLength : int

module private SubModule =
    let getLength s = String.length s

    type MyType (s: string) =
        let _str = s
        interface RootType with
            member this.GetStringLength with get() = getLength _str

let myExternalValue = SubModule.MyType("Hello") :> RootType

用法:

printfn "%d" <| RootModule.myExternalValue.GetStringLength

这篇关于类型x的可访问性小于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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