有人知道为什么这个不起作用吗(无论是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)
value = null;
。 - Andras ZoltanReturn itsCustomTextFormatter
处设置断点,并告诉我们完整的故事 :) - Daniel Mošmondorvalue
是指代 变量 的关键字。当然,你可以重新分配变量的值。 - Eric Lippertvoid M() { this.x = 123; }
只是写作优雅的方式,实际上等同于static void M(ref S _this) { _this.x = 123; }
。this
必须是调用接收器相同的变量,否则可变值类型就不可能存在。 - Eric Lippert