开发者

How to use readonly property across multiple classes

I have created a read-only property(name) in class1. How can I use this name property in class2?

Public Class Class1
ReadOnly Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Propert开发者_高级运维y

Can I directly carry this name variable value into class2? Need suggestion.


You can access this property everywhere where you have a reference to a Object of type Class1. So if your Class2 objects have a reference, they can use it.

For example:

Class Class2
    Property cls1 As New Class1

    Function getClass1Name() As String
        Return cls1.Name
    End Function
End Class

Another option is to make the property shared, because it's a value that is independent of any instance of Class1 that makes sense.

Then you can access it without an instance of Class1 via the class-name:

Class Class1
    Public Shared ReadOnly Property Name As String
        Get
            Return System.IO.Path.GetFileName("C:\Demo\Sample1")
        End Get
    End Property
End Class

Class Class2
    Function getClass1Name() As String
        Return Class1.Name
    End Function
End Class


Your Readonly property is still an instance members and cannot be shared without instantiating Class1 and looking at the property definition, it can be Shared. You can make your property Shared and use it in class2

Public Class Class1
Shared Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Property

and in class2, you can call

Dim class1Name = Class1.name


Via an instance of Class1

    Public Class Class2

      Sub New()
            Dim o As New Class1
            Dim s As String  = o.Name

      End Sub

   End Class

Here is something to read on classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜