产量与回报空 [英] Yield Return with Null
本文介绍了产量与回报空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法有选择地返回一个空了,回报率驱动的迭代器?
我想在某些情况下返回空和我不ŧ觉得这是特别的IEnumerable字符串类型。同样为int类型等感谢
静态无效的主要(字串[] args)
{$ B的IEnumerable的$ b VAR项目= GetItems();
如果(项目!= NULL)
{
的foreach(VAR在项目的项目)
{
Console.WriteLine(项目);
}
}
,否则
{
Console.WriteLine(<&空GT;);
}
}
静态的IEnumerable<串GT; GetItems()
{
如果(假)
{
收益率的回报安迪
收益率的回报詹妮弗
}
返回NULL; //< - 编译器错误:
//无法从迭代器返回一个值。
//使用yield return语句返回一个值,
//或产量突破结束迭代。
}
解决方案
如果你需要的东西像该(或扔东西像的ArgumentException
立即),您需要将您的迭代器分为两种方式:
公开的IEnumerable<串GT; GetItems(){
如果(东西)返回NULL;
返回GetItemsInternal();
}
私人的IEnumerable<串GT; GetItemsInternal(){
//与收益回报率实际迭代器放在这里。
}
Is there any way to optionally return a null with a "return yield" driven iterator?
I would like to return a null in some cases and I don't think this is particular to IEnumerable of type string. Same goes for IEnumerable of type int etc. Thanks
static void Main(string[] args)
{
var Items = GetItems();
if (Items != null)
{
foreach (var item in Items)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("<null>");
}
}
static IEnumerable<string> GetItems()
{
if (false)
{
yield return "Andy";
yield return "Jennifer";
}
return null; // <- Compiler Error:
// Cannot return a value from an iterator.
// Use the yield return statement to return a value,
// or yield break to end the iteration.
}
解决方案
If you need to things like that (or throw things like ArgumentException
immediately), you need to separate your iterator into two methods:
public IEnumerable<string> GetItems() {
if (something) return null;
return GetItemsInternal();
}
private IEnumerable<string> GetItemsInternal() {
// the actual iterator with "yield return" goes here.
}
这篇关于产量与回报空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文