任何人都知道为什么这不起作用(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)
你会对结果感到惊讶。它将打印“无”。任何人都知道为什么它不打印“某事”
这是每个建议的单元测试:
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)