DOBON.NET プログラミング道: .NET Framework, VB.NET, C#, Visual Basic, Visual Studio, インストーラ, ...

DOBON.NET

クラスのプロパティを宣言する

Visual Basic 6.0 では、Property Get、Property Let、Property Setの各ステートメントを使用してプロパティの値を取得および設定ができました。また、ByRefプロパティ引数の使用も可能でした。これに対してVB.NETではプロパティ宣言の構文が大きく異なります。下の例を参考にしてください。また、ByRefプロパティ引数の使用は出来なくなりました。

[VB.NET]
Public Class SampleClass
    Private num1 As Integer = 0
    Private num2 As Integer = 0
    Private num3 As Integer = 0
    
    'GetとSetがあるとき
    Public Property Number1() As Integer
        Get
            Return num1
        End Get
        Set(ByVal Value)
            num1 = Value
        End Set
    End Property
    
    'Getしかない時はReadOnlyを付ける
    Public ReadOnly Property Number2() As Integer
        Get
            Return num2
        End Get
    End Property
    
    'Setしかない時はWriteOnlyを付ける
    Public WriteOnly Property Number3() As Integer
        Set(ByVal Value)
            num3 = Value
        End Set
    End Property
End Class
[C#]
public class SampleClass
{
    private int num1 = 0;
    private int num2 = 0;
    private int num3 = 0;

    //getとsetがあるとき
    public int Number1
    {
        get
        {
            return num1;
        }
        set
        {
            num1 = value;
        }
    }

    //getしかない時もReadOnlyなどをつける必要はない
    public int Number2
    {
        get
        {
            return num2;
        }
    }

    //setしかない時もWriteOnlyなどをつける必要はない
    public int Number3
    {
        set
        {
            num3 = value;
        }
    }
}