为什么迭代器方法不能采用“ ref”或“ out”参数?
-
14-09-2019 - |
题
我今天早些时候尝试了:
public interface IFoo
{
IEnumerable<int> GetItems_A( ref int somethingElse );
IEnumerable<int> GetItems_B( ref int somethingElse );
}
public class Bar : IFoo
{
public IEnumerable<int> GetItems_A( ref int somethingElse )
{
// Ok...
}
public IEnumerable<int> GetItems_B( ref int somethingElse )
{
yield return 7; // CS1623: Iterators cannot have ref or out parameters
}
}
这背后的理由是什么?
解决方案
C#迭代器是内部的状态机。每次你 yield return
某些东西,您应该将您关闭的地方与本地变量的状态一起保存,以便您可以返回并从那里继续。
为了持有此状态,C#编译器创建了一个类来保存本地变量及其应继续的位置。不可能有一个 ref
或者 out
价值作为课堂中的字段。因此,如果您被允许将参数声明为 ref
或者 out
, ,在我们离开时无法保留功能的完整快照。
编辑: 从技术上讲,并非所有返回的方法 IEnumerable<T>
被认为是迭代器。只是那些使用的 yield
直接产生序列是迭代器。因此,虽然将迭代器分为两种方法是一个不错的解决方法,但它与我刚才所说的并不矛盾。外部方法(不使用 yield
直接) 不是 被认为是迭代器。
其他提示
如果您想同时从方法中返回迭代器和INT,那么解决方法是:
public class Bar : IFoo
{
public IEnumerable<int> GetItems( ref int somethingElse )
{
somethingElse = 42;
return GetItemsCore();
}
private IEnumerable<int> GetItemsCore();
{
yield return 7;
}
}
您应该注意,迭代器方法中没有任何代码(即基本上是包含的方法 yield return
或者 yield break
)执行直到 MoveNext()
枚举中的方法被调用。因此,如果您能够使用 out
或者 ref
在您的迭代方法中,您会得到这样令人惊讶的行为:
// This will not compile:
public IEnumerable<int> GetItems( ref int somethingElse )
{
somethingElse = 42;
yield return 7;
}
// ...
int somethingElse = 0;
IEnumerable<int> items = GetItems( ref somethingElse );
// at this point somethingElse would still be 0
items.GetEnumerator().MoveNext();
// but now the assignment would be executed and somethingElse would be 42
这是一个常见的陷阱,一个相关的问题是:
public IEnumerable<int> GetItems( object mayNotBeNull ){
if( mayNotBeNull == null )
throw new NullPointerException();
yield return 7;
}
// ...
IEnumerable<int> items = GetItems( null ); // <- This does not throw
items.GetEnumerators().MoveNext(); // <- But this does
因此,一个好的模式是将迭代方法分为两个部分:一个立即执行,一个包含应该懒惰的代码。
public IEnumerable<int> GetItems( object mayNotBeNull ){
if( mayNotBeNull == null )
throw new NullPointerException();
// other quick checks
return GetItemsCore( mayNotBeNull );
}
private IEnumerable<int> GetItemsCore( object mayNotBeNull ){
SlowRunningMethod();
CallToDatabase();
// etc
yield return 7;
}
// ...
IEnumerable<int> items = GetItems( null ); // <- Now this will throw
编辑:如果您真的希望行为移动迭代器会修改 ref
- 参数,您可以做这样的事情:
public static IEnumerable<int> GetItems( Action<int> setter, Func<int> getter )
{
setter(42);
yield return 7;
}
//...
int local = 0;
IEnumerable<int> items = GetItems((x)=>{local = x;}, ()=>local);
Console.WriteLine(local); // 0
items.GetEnumerator().MoveNext();
Console.WriteLine(local); // 42
在较高的级别上,REF变量可以指向许多位置,包括堆栈上的价值类型。最初通过调用迭代器方法创建迭代器的时间,而何时分配了REF变量是两个截然不同的时间。不可能保证,当迭代器实际执行时,最初通过引用传递的变量仍在附近。因此,不允许(或可验证)
其他人解释了为什么您的迭代器不能具有REF参数。这是一个简单的选择:
public interface IFoo
{
IEnumerable<int> GetItems( int[] box );
...
}
public class Bar : IFoo
{
public IEnumerable<int> GetItems( int[] box )
{
int value = box[0];
// use and change value and yield to your heart's content
box[0] = value;
}
}
如果您有几个要传递的项目,请定义一个班级以持有它们。
当我需要返回的价值从迭代项目中得出时,我已经解决了这个问题:
// One of the problems with Enumerable.Count() is
// that it is a 'terminator', meaning that it will
// execute the expression it is given, and discard
// the resulting sequence. To count the number of
// items in a sequence without discarding it, we
// can use this variant that takes an Action<int>
// (or Action<long>), invokes it and passes it the
// number of items that were yielded.
//
// Example: This example allows us to find out
// how many items were in the original
// source sequence 'items', as well as
// the number of items consumed by the
// call to Sum(), without causing any
// LINQ expressions involved to execute
// multiple times.
//
// int start = 0; // the number of items from the original source
// int finished = 0; // the number of items in the resulting sequence
//
// IEnumerable<KeyValuePair<string, double>> items = // assumed to be an iterator
//
// var result = items.Count( i => start = i )
// .Where( p => p.Key = "Banana" )
// .Select( p => p.Value )
// .Count( i => finished = i )
// .Sum();
//
// // by getting the count of items operated
// // on by Sum(), we can calculate an average:
//
// double average = result / (double) finished;
//
// Console.WriteLine( "started with {0} items", start );
// Console.WriteLine( "finished with {0} items", finished );
//
public static IEnumerable<T> Count<T>(
this IEnumerable<T> source,
Action<int> receiver )
{
int i = 0;
foreach( T item in source )
{
yield return item;
++i ;
}
receiver( i );
}
public static IEnumerable<T> Count<T>(
this IEnumerable<T> source,
Action<long> receiver )
{
long i = 0;
foreach( T item in source )
{
yield return item;
++i ;
}
receiver( i );
}