任何人都有任何想法为什么这不起作用(C#或VB.NET或其他.NET语言无关紧要)。这是我的问题的非常简化的示例(对VB.NET很抱歉):
Private itsCustomTextFormatter As String
Public Property CustomTextFormatter As String
Get
If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not'
Return itsCustomTextFormatter
End Get
Set(ByVal value As String)
If value Is Nothing Then
value = "Something"
End If
itsCustomTextFormatter = value
End Set
End Property
如果您这样做:
Dim myObj as new MyClass
Console.WriteLine(myObj.CustomTextFormatter)
您会对结果感到惊讶。它将打印“Nothing”。任何人都知道为什么它不显示“Something”
这是每个建议的单元测试:
Imports NUnit.Framework
<TestFixture()> _
Public Class Test
Private itsCustomTextFormatter As String
Public Property CustomTextFormatter As String
Get
If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not'
Return itsCustomTextFormatter
End Get
Set(ByVal value As String)
If value Is Nothing Then
value = "Something"
End If
itsCustomTextFormatter = value
End Set
End Property
<Test()>
Public Sub Test2()
Assert.AreEqual("Something", CustomTextFormatter)
End Sub
End Class
这将返回:
Test2 : Failed
Expected: "Something"
But was: null
at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
at NUnit.Framework.Assert.AreEqual(Object expected, Object actual)
最佳答案
你的评论:
'thinking this should go into the setter - strangely it does not'
指出您的错误所在。在Visual Basic中,有两种从函数返回内容的方法:
Function GetSomeValue() As String
Return "Hello"
End Function
或者
Function GetSomeValue() As String
GetSomeValue = "Hello"
End Function
将这两种样式混合在一起是完全合法的,但会造成混淆,也是一种不好的做法:
Function GetSomeValue() As String
GetSomeValue = "Hello" ' I should return Hello... '
Return "GoodBye" ' ...or perhaps not. '
End Function
如您所见,您正在将两种样式混合在 setter/getter 中。 设置该变量不调用setter;它通知运行时,当getter返回时,这是它应该返回的值。 然后,您可以使用
Return
语句覆盖该值。如果这样做时很痛,那就不要这样做。