【问题标题】:C# Action which encapsulates a method with signature void SomeFunc(class arg)C# Action 封装了一个带有签名 void SomeFunc(class arg) 的方法
【发布时间】:2011-02-01 09:56:14
【问题描述】:

它存在类似Action的东西,但可以封装带有签名的方法:

void SomeFunc(IDictionary<string,class>), I try solve this:

    private void RefreshContactList()
    {
       var freshFriends = Service.GetAllFriends(Account);

        new System.Action(RefreshContactsData(freshFriends)).OnUIThread();
    }

    private void RefreshContactsData(IEnumerable<KeyValuePair<string, UserInfo>> freshFriends)
    {
          //...
    }

【问题讨论】:

  • 我猜英语不是你的第一语言,但你能不能把这个问题解释得更清楚一点。

标签: c# delegates action


【解决方案1】:

目前还不清楚您要做什么。您的代码尝试错误地创建委托 - 您正在传递方法调用的返回值:

new System.Action(RefreshContactsData(freshFriends))

而不是方法本身:

new System.Action(RefreshContactsData)

然而,创建一个委托只是为了立即调用它是没有意义的——你可以很容易地直接调用该方法。 OnUIThread 是做什么的?你想达到什么目的?

【讨论】:

  • 我需要在 WPF 应用程序的 ListBox 控件中刷新数据,所以我必须在 UI 线程上刷新数据,因为 WPF impelements STA 模型。
【解决方案2】:

如果我理解正确,您可以使用generic Action delegate。你可以这样写:

Action<IDictionary> myAction; //with one parameter
Action<IDictionary, int> myAction2; //with two parameters

【讨论】:

    【解决方案3】:

    你不需要Action,但是Action&lt;&gt;

    new System.Action<IEnumerable<KeyValuePair<string, UserInfo>>>(RefreshContactsData).BeginInvoke(freshFriends, null, null);
    

    【讨论】:

      【解决方案4】:

      您可以使用Action&lt;&gt; 类型,它封装了一个带参数的方法,或者如果您需要返回值,则可以使用FuncFunc&lt;&gt; 类型。例如:

      static void PrintHello()
      {
        Console.WriteLine("Hello world");
      }
      
      static void PrintMessage(string message)
      {
        Console.WriteLine("Hello " + message);
      }
      
      ....
      Action hello = new Action(PrintHello);
      Action<string> message = new Action<string>(PrintMessage);
      
      hello();
      message("my world");
      

      产生:

      Hello world
      Hello my world
      

      注意动作是如何创建的,只引用封装在其中的方法,然后调用它,传递所需的参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 2019-11-23
        • 1970-01-01
        • 2022-11-05
        • 1970-01-01
        • 1970-01-01
        • 2011-12-26
        相关资源
        最近更新 更多