c# - 如何创建一个可以执行传递给它的任何其他方法的方法

标签 c# delegates action call func

我正在尝试制作一个应用程序,它将对目录中的每个文件执行某事

那个东西应该是某种方法。但由于我不知 Prop 体是哪种方法,所以我正在努力做到这一点,所以我的“迭代”方法接受任何方法的参数或某种方法引用,这样他就可以在每个文件上调用它。

重点是关于如何处理每个文件有很多选项,用户可以选择他想要的那个。这些选项也必须可以扩展,所以一周后我可能会决定添加一个新选项,这就是我需要的原因:

一种可以在事先不知道其签名的情况下调用任何方法的方法。

Actions 和 Functions 对我不起作用,因为它们需要具体的签名。委托(delegate)也是如此,据我所知并且(我认为)它们不能作为方法参数传递。

我想要实现的示例:

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.
    }
}

最佳答案

您的想法可以实现,但是执行某事的函数必须始终具有相同的签名;为此,您可以使用预定义的委托(delegate)类型。考虑以下代码段。

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
}

第一个函数可以按如下方式使用。

SomethingExecuter(FileNames, SomethingOne);
SomethingExecuter(FileNames, SomethingTwo);

希望对您有所帮助。

关于c# - 如何创建一个可以执行传递给它的任何其他方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50601351/

相关文章:

ios - SWIFT:尝试使用 objective c 类的委托(delegate)方法

java - NetBeans 声明式操作注册与节点弹出菜单

c# - 在 Xamarin.Forms 中自定义进度条外观

iphone - ios循环异步请求

c# - DateTime.TryParse API 关于日期元素分隔符或定界符的内部行为

iOS 委托(delegate)不使用 UIViewControllers

java - Android 抽屉导航/DrawerLayout...切换无法正常工作

c# - "Action?"关键字是干什么的,是不是代替了ActionResult

c# - 异步返回服务器消息到客户端

c# - 预处理器 : Get Operating System . 网络核心