0

VB.Net を使用します。

次のようなプロパティを宣言しました。

Private _name as String
Private _address as String


Public Property Name as String
   Get 
      Return _name
   End Get
   Set(value as String)
      _name = value
   End Set
End Property


 Public Property Address as String
   Get 
      Return _address
   End Get
   Set(value as String)
      _address= value
   End Set
End Property

get と set を処理する別の変数の宣言を最小限に抑えたいと考えています。この変数または関数はすべてのプロパティで使用され、すべてのプロパティの値の取得と設定をすべて処理します。

例えば:

Public Property Address as String
   Get 
      Return address /*Insert function here that can be use by all property*/
   End Get
   Set(value as String)
      address = value /*Insert function here that can be use by all property*/
   End Set
End Property

前もって感謝します。

4

2 に答える 2

2

はい、あなたは財産を持つことができます

  • バッキングフィールドなし
  • なしset(読み取り専用)
  • なしget(非常識な書き込み専用プロパティ)
  • getset...への異なるアクセス修飾子を持つ

C# でのサンプル:

class Properties
{
   // Read-only, no backing field
   public int TheAnswer { get { return 42;}}

   // Write-only, no backing field
   public bool Destroyed { set { if (value) DestroyEverything();}}

   // No backing fields with some work in properties:
   int combined;
   public int Low { 
      get { return combined & 0xFF; }
      set { combined = combined & ~0xFF | (value & 0xFF); }
   }

   public int High { 
      get { return combined >> 8; }
      set { combined = combined & 0xFF | (value << 8); }
   }

   void DestroyEverything(){} 
}

MSDNの VB.Net サンプル- 方法: プロパティを作成する

Dim firstName, lastName As String 
Property fullName() As String 
    Get 
      If lastName = "" Then 
          Return firstName
      Else 
          Return firstName & " " & lastName
      End If 

    End Get 
    Set(ByVal Value As String)
        Dim space As Integer = Value.IndexOf(" ")
        If space < 0 Then
            firstName = Value
            lastName = "" 
        Else
            firstName = Value.Substring(0, space)
            lastName = Value.Substring(space + 1)
        End If 
    End Set 
End Property
于 2013-07-30T03:01:23.630 に答える
0

C#では、短い形式でプロパティを定義できます

public string Name{get; set;}

コンパイラーはそのバッキングフィールドを作成し、次のような単純なゲッターとセッターに拡張します

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }
}

もちろん、getter と setter の両方のショートカットにアクセス修飾子を提供することも、しないこともできます。

public string Name{ internal get; protected set;}
于 2013-07-30T02:57:49.003 に答える