Как вызвать Linq Take () над базовым классом IEnumerable? - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь: RandomBytes генерирует случайные байты (то есть, это перечислимо). RandomNBytes - это то же самое, но N случайных байтов (оно расширяет RandomBytes). Итак, код:

class RandomBytes : IEnumerable<byte>, IEnumerable {
    public IEnumerator<byte> GetEnumerator() {
        var rnd = new Random();
        while (true) {
            yield return (byte)rnd.Next(0, 255);
        }
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return this.GetEnumerator();
    }
}

class RandomNBytes : RandomBytes {
    readonly UInt64 Count;

    RandomNBytes (UInt64 count) {
        Count = count;
    }

    public new IEnumerator<byte> GetEnumerator() {
        return ((IEnumerable<byte>)base).Take(Count);
    }
}

Но есть проблема с base, VC ​​выдает ошибку: использование ключевого слова "base" недопустимо в этом контексте. Как вызвать Take() сверх перечислимого базового класса?

1 Ответ

0 голосов
/ 02 мая 2018

Я бы сделал это так:

public class RandomBytes : IEnumerable<byte>, IEnumerable
{
    public IEnumerator<byte> GetEnumerator()
    {
        //used null, but could also drop the nullable and just pass ulong.MaxValue into the method
        return GetEnumerator(null);
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    //extracted the "main" method to a seperate method that takes a count
    protected IEnumerator<byte> GetEnumerator(ulong? count)
    {
        //use ulong.MaxValue when null gets passed, 
        //what ever you are doing with this code 18,446,744,073,709,551,615 iterations should be enough
        var c = count ?? ulong.MaxValue; 

        var rnd = new Random();
        for (ulong i = 0; i < c; i++)
            yield return (byte)rnd.Next(0, 255);
    }
}

public class RandomNBytes : RandomBytes
{
    readonly ulong Count;

    public RandomNBytes(ulong count)
    {
        Count = count;
    }

    public new IEnumerator<byte> GetEnumerator()
    {
        return GetEnumerator(Count); //call the protected method
    }
}
...