Do you have a blind spot in programming?
I mean, is there a common technique or language feature that you can't get used to. Well, I have one (or maybe more than one), and mine is use delegate. Hands up! Who else does not feel comfortable with delegates? Be honest!
So what is a delegate?
Since my university courses introduced me to C, I know about function pointers. Function pointers are useful if you want to pass methods as arguments. Therefore, in my opinion, a delegate is something like a pointer to a function. Eureka! I understood. I do not have!
Specific scenario?
I would like to remove any line from a text file that matches the regular expression . Assuming I have a set of strings, there List<T>is a method RemoveAllthat seems to be perfect for this purpose.
RemoveAllexpects an evaluation method as an argument for deciding whether to remove or leave a list item. And here it is: a 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;
}
So, I'm looking for a function DoesLineMatchthat evaluates a string to match a pattern.
Do you see the problem?
RemoveAllexpects a delegate Predicate<string> matchas an argument. I would encode this as follows:
private static bool DoesLineMatch(string line, string pattern)
{
return Regex.IsMatch(line, pattern);
}
But then I get the error message "Expected method with 'bool DoesLineMatch (string)' signature '. What am I missing here?
Does it work at all?
Here is how I finally got the job:
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;
}
, , .
?
, , , - .
, - ---destroy.
, , .
? ?
PS: , .
PPS: , 2.0 3.0 lambdas.
PPPS: Regex.IsMatch(string, string) :
int result = lines.RemoveAll(delegate(string line)
{
Regex regex = new Regex(pattern);
return regex.IsMatch(line);
});
. ReSharper Regex :
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 ( , ) .