简体   繁体   English

VB.NET:使用 Class 名称作为表达式

[英]VB.NET: Use Class Name as Expression

I'm not sure if this is possible but I would like to associate a class name reference to a shared member method / property / variable.我不确定这是否可行,但我想将 class 名称引用关联到共享成员方法/属性/变量。 Consider:考虑:

Public Class UserParameters

    Public Shared Reference As Object

    Public Shared Function GetReference() As Object
        Return Reference
    End Function

End Class

In another part of the program I would like to simply call UserParameters and have it return Reference either by aliasing GetReference or the variable directly.在程序的另一部分,我想简单地调用 UserParameters 并让它返回 Reference 通过别名 GetReference 或直接变量。

I am trying to emulate the Application, Request, or Session variable: Session(0) = Session.Item(0)我正在尝试模拟应用程序、请求或 Session 变量:Session(0) = Session.Item(0)

Any suggestions would be greatly appreciated.任何建议将不胜感激。

You can't return an instance member from a static method directly (the static method can't access instance members because it isn't instantiated with the rest of the class, only one copy of a static method exists). You can't return an instance member from a static method directly (the static method can't access instance members because it isn't instantiated with the rest of the class, only one copy of a static method exists).

If you need to setup a class in such a way that you can return an instance from a static method you would need to do something similar to the following:如果您需要设置 class 以使您可以从 static 方法返回实例,则需要执行类似于以下的操作:

Public Class SampleClass

    Private Sub New()
        'Do something here
    End Sub

    Public Shared Function GetSample() As SampleClass
        Dim SampleClass As SampleClass
        SampleClass = New SampleClass

        SampleClass.Sample = "Test"

        Return SampleClass
    End Function

    Private _SampleString As String
    Public Property Sample As String
        Get
            Return _SampleString
        End Get
        Private Set(ByVal value As String)
            _SampleString = value
        End Set
    End Property

End Class

Public Class SampleClass2

    Public Sub New()
        'Here you can access the sample class in the manner you expect
        Dim Sample As SampleClass = SampleClass.GetSample
        'This would output "Test"
        Debug.Fail(Sample.Sample)
    End Sub
End Class

This method is used in various places in the CLR.此方法在 CLR 中的各个地方使用。 Such as the System.Net.WebRequest class .例如System.Net.WebRequest class where it is instantiated in this manner in usage:在使用中以这种方式实例化的地方:

' Create a request for the URL.         
        Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM