Chiunque ha qualche idea del perché questo non funziona (C# o VB.NET o altro linguaggio .NET non importa). Questo è un esempio molto semplificato del mio problema (mi dispiace per VB.NET):Comportamento proprietà interessante
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
Se lo fai:
Dim myObj as new MyClass
Console.WriteLine(myObj.CustomTextFormatter)
Sarete sorpresi del risultato. Stamperà "Niente". Qualcuno ha qualche idea del perché non viene stampata "Something"
Ecco un test unitario per suggerimento:
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
Ciò restituisce:
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)
Sono sorpreso che 'value =" Something "' compili. Hmm sembra che 'value' non sia una parola chiave in VB.net, ma solo un parametro normale, che spiega che compila. – CodesInChaos
È una stringa, non è necessario "Nuovo" quando lo si imposta – Denis
@CodeInChaos in C# si può fare 'value = null;' in un setter –