Do you have a blind spot in programming?
I mean is there a common technique or language feature that you can t really get used to.
Well, I have one (or probably more than one) and mine is usage of delegate
.
Hands up! Who else doesn t feel comfortable with delegates? Be honest!
So what s a delegate?
Since my courses at university introduced me to C, I know about function pointers. Function pointers are handy if you want to pass methods as arguments. So in my mind a delegate is something like a function pointer. Eureka! I got it. I have not!
A concrete scenario?
I would like to remove any line from a text file that matches a regular expression.
Assuming I have a collection of lines, List<T>
has method RemoveAll
which seems to be perfectly suitable for that purpose.
RemoveAll
expects an evaluation method as argument for deciding on whether to remove or leave a list element.
And there it is: The function pointer!
Any code here?
public static int RemoveLinesFromFile(string path, string pattern)
{
List<string> lines = new List<string>(File.ReadAllLines(path));
int result = lines.RemoveAll(DoesLineMatch);
File.WriteAllLines(path, lines.ToArray());
return result;
}
因此,Im 寻找一种功能:DoesLineMatch
,如果一条线与一种模式相匹配,则对其进行评价。
Do you see the problem?
RemoveAll
expects a delegate Predicate<string> match
as argument.
I would have coded it like this:
private static bool DoesLineMatch(string line, string pattern)
{
return Regex.IsMatch(line, pattern);
}
But then I m getting an error "Expected a method with bool DoesLineMatch(string) signature". What am I missing here?
Does it work at all?
这是我最后如何工作:
public static int RemoveLinesFromFile(string path, string pattern)
{
List<string> lines = new List<string>(File.ReadAllLines(path));
int result = lines.RemoveAll(delegate(string line)
{
return Regex.IsMatch(line, pattern);
});
File.WriteAllLines(path, lines.ToArray());
return result;
}
我高兴的是,它发挥了作用,但我不理解它。
And what is the question?
What I did to get it working is simply inlining the method. As far as I understand inlining, it is just some kind of use-once-and-destroy-code. If you use a variable or method only once you may inline it, but inlining is always equivalent to declaring it explicitly.
www.un.org/Depts/DGACM/index_spanish.htm 是否有办法明确宣布这种方法? 我如何做?
PS:请允许我说,我的问题有些漫长。
PPS.:一俟我收到这一授权,我将从2.0跃到3.0,并学习拉姆比斯。
PPPS:以下网站:Jon s hint。 我修改了我的法典:
int result = lines.RemoveAll(delegate(string line)
{
Regex regex = new Regex(pattern);
return regex.IsMatch(line);
});
在效率问题上,这没有什么帮助。 因此,我遵循ReSharper的建议,并将Reexspeiation移至外部:
Regex regex = new Regex(pattern);
int result = lines.RemoveAll(delegate(string line)
{
return regex.IsMatch(line);
});
现在,ReSharper敦促我用一个方法组取代:
Regex regex = new Regex(pattern);
int result = lines.RemoveAll(regex.IsMatch);
这与这里提出的答案相当相似。 我不要求什么,但我再次感到惊讶的是,ReSharper(当然还有Stack Overflow)如何帮助学习。