我如何使用 C# 中的单个方法 return N 个 IEnumerable<bool> 值?

How would I return N number of IEnumerable<bool> value with a single method in C#?

任务:

这是我目前尝试过的方法:

IBoolS.cs:

public interface IBoolS
{
   public IEnumerable<bool> GetBools(int N)
    {
        //what goes here? yield return something, but what?
    }
}

Generator.cs:

public class Generator : IBoolS
{
    private bool ValueToGenerate;

    //GetBools(N pieces of ValueToGenerate);, but should be an integer number
}

接口只是一个声明,一个合同用于实现它的class(es):

public interface IBoolS
{
   IEnumerable<bool> GetBools(int N);
}

class 实现接口:

public class Generator : IBoolS
{
    // Let's have a property instead of field: which value is generated
    public bool ValueToGenerate {get;}

    // Do not forget a constructor - we have to set ValueToGenerate
    public Generator(bool valueToGenerate) {
      ValueToGenerate = valueToGenerate;
    }    

    // Interface implementation: we generate N bool values
    public IEnumerable<bool> GetBools(int N) {
      // Input validation
      if (N < 0)
        throw new ArgumentOutOfRangeException(nameof(N));

      // Shorter version is
      // return Enumerable.Repeat(ValueToGenerate, N);
      for (int i = 0; i < N; ++i)
        yield return ValueToGenerate; 
    } 
} 

听起来你只需要 Enumerable.Repeat:

public interface IBoolS
{
   IEnumerable<bool> GetBools(int N);
}

public class Generator : IBoolS
{
    public bool ValueToGenerate { get; set; }

    public IEnumerable<bool> GetBools(int N) => Enumerable.Repeat(ValueToGenerate, N);
}

这是一种可能的实现方式(虽然不是高性能的实现方式):

public interface IBoolS
{
    IEnumerable<bool> GetBools(int N);
}

public class Generator : IBoolS
{
    private bool _valueToGenerate;
    
    public Generator(bool valueToGenerate) {
        _valueToGenerate = valueToGenerate;
    }

    public IEnumerable<bool> GetBools(int N) {
        foreach (var n in Enumerable.Range(0, N)) {
            yield return _valueToGenerate;
        }                        
    }
}