yüzden, Jason'ın çözümüne benzer bir şey önermek, ancak bunun yerine IDataReader uygulayan bir sarmalayıcı kullanarak olacaktır: Bu tüm etkilenmeyen özellikleri için geçiş kodunu biraz gerektirirken
sealed public class PeekDataReader : IDataReader
{
private IDataReader wrappedReader;
private bool wasPeeked;
private bool lastResult;
public PeekDataReader(IDataReader wrappedReader)
{
this.wrappedReader = wrappedReader;
}
public bool Peek()
{
// If the previous operation was a peek, do not move...
if (this.wasPeeked)
return this.lastResult;
// This is the first peek for the current position, so read and tag
bool result = Read();
this.wasPeeked = true;
return result;
}
public bool Read()
{
// If last operation was a peek, do not actually read
if (this.wasPeeked)
{
this.wasPeeked = false;
return this.lastResult;
}
// Remember the result for any subsequent peeks
this.lastResult = this.wrappedReader.Read();
return this.lastResult;
}
public bool NextResult()
{
this.wasPeeked = false;
return this.wrappedReader.NextResult();
}
// Add pass-through operations for all other IDataReader methods
// that simply call on 'this.wrappedReader'
}
Not Ancak faydası, sonuç kümesindeki herhangi bir pozisyonda, sonraki 'okuma' işleminde ilerlemeden 'göz atabilecek' genel bir soyutlama olmasıdır.
kullanmak için:
using (IDataReader reader = new PeekDataReader(/* actual reader */))
{
if (reader.Peek())
{
// perform some operations on the first row if it exists...
}
while (reader.Read())
{
// re-use the first row, and then read the remainder...
}
}
Not her 'Peek()' çağrısı aslında bir sonraki kayda hareket edecek olsa önceki operasyonu aynı zamanda bir 'Peek()' olmasaydı. Bu simetriyi 'Read()' işlemi ile sürdürmek daha basit bir uygulama ve daha zarif bir API sağlar.
Örneğiniz, 'IDataReader' arabiriminin kendisi '.Peek 'yöntemini içermediği için çalışmaz. Açık alan değişkenini "PeekDataReader" veya "var" olarak kullanmanız gerekir. – julealgon