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

我想最小化声明另一个将处理获取和设置的变量。此变量或函数将被所有属性使用,并将处理所有属性的所有获取和设置值。

例如:

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;}

编译器将为它创建支持字段并扩展为简单的 getter 和 setter

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 回答