开发者

Using ref parameters in linq

I have a function that takes a ref parameter and would like to use it in a linq query but the compiler complains.

The function is called BreakLine and breaks a string up into lines based on a line length, the ref parameter is used to keep track of where it is in the string on each call:

string BreakLine(s开发者_如何学JAVAtring text, int lineLimit, ref offset);

The query is:

from pt in productText 
let offset = 0
from ll in lineLimits
select new Line() { Text = BreakLine(pt, ll, ref offset) }

(Line is a simple data class)

The error is:

"Cannot pass the range variable 'offset' as an out or ref parameter"

Any way to workaround this?


The parameter offset has no type specified. Try to change the BreakLine method signature into this:

string BreakLine(string text, int lineLimit, ref int offset);

...but I guess that is just a typo in your question. The real problem you have is that you get compiler error CS1939. Quote from the documentation:

A range variable is a read-only variable that is introduced in a query expression and serves as an identifier for each successive element in a source sequence. Because it cannot be modified in any way, there is no point in passing it by ref or out. Therefore, both operations are not valid.


Func<string, int, Line> lineFunc = (pt, ll) =>
{
    int offset = 0;
    return new Line() { Text = BreakLine(pt, ll, ref offset) };
};
var test = from pt in productText
            from ll in lineLimits
            select lineFunc(pt, ll);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜