有趣的财产行为

Den*_*nis 5 .net c# vb.net

任何人都有任何想法为什么这不起作用(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
Run Code Online (Sandbox Code Playgroud)

如果你这样做:

Dim myObj as new MyClass
Console.WriteLine(myObj.CustomTextFormatter)
Run Code Online (Sandbox Code Playgroud)

你会对结果感到惊讶.它将打印"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
Run Code Online (Sandbox Code Playgroud)

返回:

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)
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 13

你的评论:

'thinking this should go into the setter - strangely it does not'    
Run Code Online (Sandbox Code Playgroud)

调出你的错误.在Visual Basic中,有两种方法可以从函数中返回一些内容:

Function GetSomeValue() As String
    Return "Hello"
End Function
Run Code Online (Sandbox Code Playgroud)

要么

Function GetSomeValue() As String
    GetSomeValue = "Hello"
End Function
Run Code Online (Sandbox Code Playgroud)

混合这两种风格是完全合法的,但令人困惑和不好的做法:

Function GetSomeValue() As String
    GetSomeValue = "Hello" ' I should return Hello... '
    Return "GoodBye"       ' ...or perhaps not. '
End Function
Run Code Online (Sandbox Code Playgroud)

如您所见,您正在混合getter中的两种样式.设置该变量不会调用setter; 它通知运行时当getter返回时,这是它应该返回的值.然后使用Return语句覆盖该值.

如果你这样做会疼,那就不要这样做了.