Reputation: 1317
I am trying to make an application that will do something on every file in a directory.
That something should be some method. But since I don't know which method, exactly, I am trying to make it so my "iterating" method takes an argument of any method or some sort of method reference, so he can call it on every file.
The point is that there are many options on what to do with each file and the user chooses the one he wants. The options must also be open for extension, so a week from now I may decide to add a new one, that is why I need:
A method that can call any method with no prior knowledge of its signature.
Actions and Functions on't work for me, because they need a concrete signature. So do delegates, as far as I know and (I think) they can't be passed as a method parameter.
Example of what I want to achieve:
void Iterate(DirectoryInfo dir, method dostuff)
{
foreach(var file in dir.GetFiles())
{
dostuff(file);
//And this is the point where I feel stupid...
//Now I realise I need to pass the methods as Action parameters,
//because the foreach can't know what to pass for the called method
//arguments. I guess this is what Daisy Shipton was trying to tell me.
}
}
Upvotes: 1
Views: 150
Reputation: 17605
Your idea can be implemented, however the function which does something must always have the same signature; for this you could use the predefined delegate types. Consider the following snippet.
public void SomethingExecuter(IEnumerable<string> FileNames, Action<string> Something)
{
foreach (string FileName in FileNames)
{
Something(FileName);
}
}
public void SomethingOne(string FileName)
{
// todo - copy the file with name FileName to some web server
}
public void SomethingTwo(string FileName)
{
// todo - delete the file with name FileName
}
The first function could be used as follows.
SomethingExecuter(FileNames, SomethingOne);
SomethingExecuter(FileNames, SomethingTwo);
I hope this helps.
Upvotes: 4