在.NET中,有没有一种情况是我应该使用以下方式而不是使用具有读/写功能的属性?
private S as string
public function GetS() as string
return S
end function
public sub SetS(byval NewS as string)
S = NewS
end function
属性是否只是提供了做同样事情的更高效方法?
在高性能应用中,属性是否比上述访问器函数慢?
在.NET中,有没有一种情况是我应该使用以下方式而不是使用具有读/写功能的属性?
private S as string
public function GetS() as string
return S
end function
public sub SetS(byval NewS as string)
S = NewS
end function
属性是否只是提供了做同样事情的更高效方法?
在高性能应用中,属性是否比上述访问器函数慢?
在内部,属性实际上就是一对方法。它们基本上等同于get和set访问器方法。
除非属性可能会导致意外的、潜在的长时间运行的副作用,或者有其他充分理由使用方法,否则应该使用属性。
有关详细信息,请阅读MSDN上的属性使用指南。特别是在以下情况下使用方法:
否则,我会使用属性。 Brad Abram在其博客中列出了一些其他细节,包括某些API函数使用方法的充分理由(主要是因为它们可能会导致跨计算机通信,这属于“副作用”类别)。
在使用属性或函数时,另一个决定是实例化父对象。VB具有极为方便的语法,例如:
Dim MyStudent as Student With {.Name = "Bobby", .Age = 10}
在 With 部分只有属性可用。
我维护一个应用程序,其中有许多持久化对象存储在数据库中,这些对象之间存在很多关系。例如,一个学生有一位老师,而这名老师被持久化在数据库中。
通常我会使用 WriteOnly 属性来设置教师,因为这是一个轻量级的操作,但是由于检索教师可能需要昂贵的数据库访问,所以我使用一个函数来检索。换句话说:
Public Writeonly Property Teacher() as Teacher
Public Function GetTeacher() as Teacher
With { .Teacher = SomeTeacherObject }
的形式实例化一个学生,但是GetTeacher鼓励在用户代码中缓存教师对象并不仅仅将其作为一个属性使用,这可能会导致多次数据库访问调用。属性其实只是叫做 get_MyProperty
和 set_MyProperty
的方法的语法糖,因此在性能上没有区别。
是的,在我的经验中,我尽量避免使用属性,而是使用函数和例程代替。以下是我这样做的原因:
Less Code, while it's not a HUGE amount, defining properties in VB requires at least 2 extra lines of code per get or set. The Overhead is double the lines of actual code for a single assignment or return operation. Although small this makes reading code much more difficult, VB is already an obsessively wordy language.
Private ReadOnly Property Foo As String
Get
Return Bar
End Get
End Property
vs
Private Function Foo As String
Return Bar
End Function
Properties are less flexible you must return what the same value you get. In Other words you can't set the value using a String
and get using an Integer
or overload setting with a String
, or an Integer
.
公正地说,我使用属性的原因是为了获得设置的=
语法,但当您拥有只读属性时,这种语法并不适用。此外,属性可以在VS编辑器的属性对话框中设置。
使用N-Tier设计,在我的BO中,我将属性值存储为未设置的值,然后在第一次访问时进行设置。
Private _aValue As integer =-1
Private ReadOnly Property aValue As integer
Get
If _aValue = -1 Then
_aValue = DA.General.GetaValue()
End If
Return _aValue
End Get
End Property
这样,我就不必担心是否按正确顺序解析属性,因为我基本上是惰性加载它们。