gpt4 book ai didi

c# - 有趣的属性行为

转载 作者:太空狗 更新时间:2023-10-29 22:14:27 25 4
gpt4 key购买 nike

任何人都知道为什么这不起作用(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)

您会对结果感到惊讶。它将打印“无”。任何人都知道为什么它不打印“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

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

如果您这样做时感到疼痛,那么不要那样做

关于c# - 有趣的属性行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10319135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com