首页 > 解决方案 > 我将如何返回 N 个 IEnumerableC# 中单个方法的值?

问题描述

任务:

这是我迄今为止尝试过的:

IBoolS.cs:

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

生成器.cs:

public class Generator : IBoolS
{
    private bool ValueToGenerate;

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

标签: c#.netienumerableyield-return

解决方案


接口只是一个声明,是实现它的类的契约

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; 
    } 
} 

推荐阅读