【问题标题】:Passing Actions into generic functions将动作传递给泛型函数
【发布时间】:2016-04-06 23:04:59
【问题描述】:

我试图通过尝试不同的东西来围绕 Csharp 中的不同概念。 A 创建一个接受动作的通用函数。该操作有一个输入参数并返回 void。我创建了一个链接到 lambda 函数的简单操作(返回 void 有一个参数 x)。我能够运行该操作,但是当我将函数传递给我的通用函数时,我不确定如何添加输入参数。 act("Some Int") 不起作用。

如何将值传递给操作?

public MainWindow()
    {
        InitializeComponent();

        Action<int> myAction = (x) => Console.WriteLine(x);
        myAction(13);
        test(myAction);
    }

    private static void test<T>(Action<T> act)
    {
        act(); // How do i pass in an int Here?
    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    只需调用act("Some Int"),因为您刚刚要求Action 行为是一个通用函数。因此,您不能使用一种固定变量类型专门调用它。你可以通过修改test-method来解决你的问题

     private static void test<T>(Action<T> act, T value)
     {
        act(value); // How do i pass in an int Here?
     }
     ...
     test(myAction,integerValue);
    

    现在您可以使用给定的int值调用Action

    【讨论】:

      【解决方案2】:

      我可以看到您正在尝试做什么,只是想抛出这种模式,因为当我们必须使用闭包并且参数可能大不相同时,我们经常这样做。

      在这些情况下,与其定义Action&lt;T&gt; 来限制您使用闭包,您只需将您的方法定义为Action。所以test 看起来像这样:

      private static void test(Action act)
      {
          act(); // yup, that's all there is to it!
      }
      

      那么你将如何传递参数?很简单:使用闭包。像这样:

      public MainWindow()
      {
          InitializeComponent();
      
          var x = 13; // this defined outside now...
      
          Action myAction = () => Console.WriteLine(x); // you're basically using the closure here.
      
          myAction();
      
          test(myAction);
      }
      

      当我们进行上下文切换(也称为线程跳转)时,我们经常使用这种方法,并且需要线程继续在其执行时获取一个或多个变量值。这只是一个例子,还有很多其他有效的用例。

      您的实验示例,如果我没看错的话,也可以作为闭包非常合适的情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 2020-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多