c# - 我将如何返回 N 个 IEnumerableC# 中单个方法的值?
问题描述
任务:
使用一个名为 GetBools 的方法创建一个名为 IBoolS 的公共接口:参数 int N,返回值 IEnumerable。
创建一个名为 Generator 的公共类,该类通过一个名为 ValueToGenerate 的布尔属性来实现此接口,这里的 GetBools 方法应该返回 N 个 ValueToGenerate。
这是我迄今为止尝试过的:
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
}
解决方案
接口只是一个声明,是实现它的类的契约:
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;
}
}
推荐阅读
- javascript - 设置自定义图像从底部到顶部条形图的内部条形(使用高图)?
- java - Hazelcast Jet 是否允许从 rollingAggregate 查询累加器值?
- ios - 私人 Pod 安装
- sorting - Yii2无法在计算值中排序
- javascript - 匹配一个元素并包装匹配元素之前的其他内容
- react-native - 当应用程序在前台时,linking.addEventListener 不适用于 ios
- python - 在 django 和 pythonanywhere 中经常重复后台任务的最佳实践
- c# - 如何最好地将异步客户端/请求配置注入 NSwag 客户端代码
- react-native - 如何解决 react-native 中的问题“BatchedBridge”?
- python - ZIP 目录:shutil.rmtree()