delegates in C#
i have 3 files that i need to compare to 100 oth开发者_StackOverflow中文版er files (by using some functions i wrote). i take each file from the three and in loop compare them to each one of the 100 files. i want to use the functions sequentially, after i finish to compare the 3 files to the 100 files i want to activate the next function, how can i do it ( the signature of the functions are the same so i can use delegate, but i don't know how) here is a pseudo code for the comparison:
for(i=0;i<3;i++)
{
for(j=0;j<100;j++)
compare(filesArr1[i],filesArr2[j]);
}
After the two loops ended i want to activate the next compare function...
Okay, so basically you're trying to parameterise a common method by the comparison. Something like this should work for you:
public void CompareFiles(IEnumerable<string> firstFiles,
IEnumerable<string> secondFiles,
Action<string, string> comparison)
{
foreach (string file1 in firstFiles)
{
foreach (string file2 in secondFiles)
{
comparison(file1, file2);
}
}
}
Then call it with:
CompareFiles(arrFiles1, arrFiles2, FirstComparison);
CompareFiles(arrFiles1, arrFiles2, SecondComparison);
That's assuming the comparison method already takes any appropriate action. If it needs to return something, you'll probably want to use a Func
of some description - more details would be useful.
The following code will run the loop you provided twice; the first time calling comp1, and the second time calling comp2. You can increase the number of comparison functions by a) writing more, and b) adding their names to the following line:
ComparisonDelegate[] comparisons = new ComparisonDelegate[] { comp1, comp2 };
delegate bool ComparisonDelegate(string file1, string file2);
static bool comp1(string file1, string file2) { return true; }
static bool comp2(string file1, string file2) { return false; }
ComparisonDelegate[] comparisons = new ComparisonDelegate[] { comp1, comp2 };
void runComparisons()
{
foreach (ComparisonDelegate cd in comparisons)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 100; j++)
{
bool retVal = cd(filesArr1[i], filesArr2[j]);
}
}
}
}
Hopefully you can adapt this to suit
1st of all it would be much faster if your main and only loop will go through 100 files and inside it you will compare your 3 files ;) Like this:
for( int index = 0; index < 100; index++ )
{
// then all actions here
}
Next. If you need to switch to another comparison function after some steps, you need to change your working delegate switching to some other function. But there's no difference on whether you switch your delegate or call another function, you just need another function call for 3rd file in your case. You need better formalization why you need to switch and on what premises this depends.
If you know after how many iterations you want to change the compare function, you can do a basic if (or switch ), no need for delegates:
if ( 0 < j ) && ( j < 2)
compare1()
else
if (2 < j) && ( j < 10)
compare2()
else
compare3()
精彩评论