Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 如果我在一个模块内有一个函数,它返回一个自定义结构,那么我可以使该结构在模块外不可访问吗?_Vb.net - Fatal编程技术网

Vb.net 如果我在一个模块内有一个函数,它返回一个自定义结构,那么我可以使该结构在模块外不可访问吗?

Vb.net 如果我在一个模块内有一个函数,它返回一个自定义结构,那么我可以使该结构在模块外不可访问吗?,vb.net,Vb.net,我有一个关于范围的问题 假设我有以下模块: Public Module SampleModule Public Function SampleFunction() As SampleStructure Return New SampleStructure(123, 456) End Function Structure SampleStructure 'Do not want this accessible elsewhere in project

我有一个关于范围的问题

假设我有以下模块:

Public Module SampleModule

    Public Function SampleFunction() As SampleStructure
        Return New SampleStructure(123, 456)
    End Function

    Structure SampleStructure 'Do not want this accessible elsewhere in project
        Public A As Integer
        Public B As Integer
        Sub New(ByVal A As Integer, ByVal B As Integer)
            Me.A = A
            Me.B = B
        End Sub
    End Structure

End Module
函数
SampleFuncton()
是整个项目中唯一需要创建
SampleStructure
新实例的代码。我希望函数可以在项目中的任何地方访问,但我不希望结构可以在任何地方访问,也不希望它在Intellisense的任何其他地方显示


这可能吗?不,不可能。您正在返回结构的实例,因此程序的其他部分需要具有可见性。否则,他们将如何与它交互,或者如何知道函数返回的是什么类型


如果您没有返回实例,可以将其设置为私有。

如果您真正想做的是阻止其他程序集创建
SampleStructure的实例,则您正在查找access修饰符

SampleStructure
的构造函数更改为以下内容

Friend Sub New(ByVal A As Integer, ByVal B As Integer)
    Me.A = A
    Me.B = B
End Sub

如果您真的想让结构只在程序集内部可访问,但仍能让外部世界访问该功能,那您就太倒霉了。

我想与大家分享另一种方法。以下所有代码都应放在模块中

1)创建一个可公开所有属性、方法、函数等的文件,以便访问

Public Interface Sample
    ReadOnly Property A() As Integer
    ReadOnly Property B() As Integer
End Interface
2)创建一个私有结构并实现
Sample
接口

Private Structure InternalSample
    Implements Sample
    Friend Sub New(ByVal A As Integer, ByVal B As Integer)
        Me.m_a = A
        Me.m_b = B
    End Sub
    Public ReadOnly Property A() As Integer Implements Sample.A
        Get
            Return Me.m_a
        End Get
    End Property
    Public ReadOnly Property B() As Integer Implements Sample.B
        Get
            Return Me.m_a
        End Get
    End Property
    Friend m_a As Integer
    Friend m_b As Integer
End Structure
3)
GetSample
函数中,创建
InternalSample
的新实例,设置所需值并返回对象

Public Function GetSample() As Sample
    Dim struct As New InternalSample(123, 456)
    'You can still change the values before returning the object:
    struct.m_a = 321
    struct.m_b = 654
    Return struct
End Function

好吧,这个想法是让它在某种意义上是只读的。因此,您可以读取结构,但不能实例化它。所以你可以写
Dim TestValue as Integer=SampleFunction()。我知道,这没有多大意义。我在过去遇到过类似的需求,我只是想问一下。那样的话,你可以交构造器的朋友。但这只会使它隐藏在当前的程序集之外好的,谢谢。我不认为这是可能的,但我想我还是会问。换一个词,再加上两个词,你就有了一个合适的班级,你可以做任何事情