大家好我是新來的C#語言,我是用vb.net, 下面這有什麼代碼,爲什麼錯誤,謝謝的IEnumerator IEnumerable的VB到C#
vb.net code
Class SplitString
Implements IEnumerable
Implements IEnumerator
Private currentPosition As Integer = 0
Private m_Sentence As String
Property Sentence() As String
Get
Return m_Sentence
End Get
Set(ByVal Value As String)
m_Sentence = Value
Me.Reset()
End Set
End Property
Public ReadOnly Property Current As Object Implements IEnumerator.Current
Get
Dim counter As Integer
Dim tmpLength As Integer = 0
For counter = Me.currentPosition To Me.Sentence.Length - 1
If Me.Sentence.Chars(counter) = " "c Then
Exit For
Else
tmpLength += 1
End If
Next
Current = Me.Sentence.Substring(Me.currentPosition, tmpLength) ' ok
Me.currentPosition += tmpLength + 1
End Get
End Property
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
If Me.currentPosition > Me.Sentence.Length - 1 Then
Me.Reset()
Return False
Else
Return True
End If
End Function
Public Sub Reset() Implements IEnumerator.Reset
Me.currentPosition = 0
End Sub
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Me
End Function
End Class
但是當我嘗試此代碼爲C#我得到錯誤
c# code
class SplitString:IEnumerable,IEnumerator
{
private int currentPosition = 0;
private string m_Sentence;
public string Sentence
{
get { return m_Sentence; }
set
{
m_Sentence = value;
this.Reset();
}
}
public IEnumerator GetEnumerator()
{
return this;
}
public object Current
{
get
{
int counter = 0;
int tmpLength = 0;
for (counter = this.currentPosition; counter <= this.Sentence.Length - 1; counter++)
{
if (this.Sentence[counter] == ' ')
{
break;
}
else
{
tmpLength += 1;
}
}
Current = this.Sentence.Substring(this.currentPosition, tmpLength); // Error
this.currentPosition += tmpLength + 1;
return functionReturnValue;
}
}
public bool MoveNext()
{
if (this.currentPosition > this.Sentence.Length-1)
{
this.Reset();
return false;
}
else
{
return true;
}
}
public void Reset()
{
this.currentPosition=0;
}
}
錯誤:屬性或索引器「Example.splitstring.current」不能已經分配到 - 它是隻讀
嘗試用'var functionReturnValue = this.Sentence.Substring'替換'Current = this.Sentence.Substring ...'# –
@YacoubMassad感謝ycoub先生,但爲什麼我不得不寫「function Return Value」我想要準確理解爲什麼發生此錯誤 –
有趣。我想這與VB6的向後兼容性有關。在那裏你可以給方法名分配一個值,而不是返回它。所以這隻適用於只讀屬性getter,無處可用。 –