user572844
user572844

Reputation:

C# Action which encapsulates a method with signature void SomeFunc(class arg)

It exist something like Action but which can encapsulate method with signature:

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)
    {
          //...
    }

Upvotes: 3

Views: 2539

Answers (4)

Rafal Spacjer
Rafal Spacjer

Reputation: 4918

If I understand you correctly you can use generic Action delegate. You can write then:

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

Upvotes: 2

SWeko
SWeko

Reputation: 30892

You can use the Action<> type, which encapsulates a method taking a parameter, or if you need a return value, the Func and Func<> types. For example:

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");

produces:

Hello world
Hello my world

Note how the action is created, just referencing the method that is encapsulated within, and then it's invoked, passing the required parameter.

Upvotes: 0

Dimitris Tavlikos
Dimitris Tavlikos

Reputation: 8170

You do not need Action, but Action<>:

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

Upvotes: 0

EMP
EMP

Reputation: 61971

It's not really clear what you're trying to do. Your code tries to create a delegate incorrectly - you are passing in the return value of a method invocation:

new System.Action(RefreshContactsData(freshFriends))

instead of the method itself:

new System.Action(RefreshContactsData)

However, there would be no point in creating a delegate only to call it immediately - you could just as easily call the method directly. What does OnUIThread do? What are you trying to achieve?

Upvotes: 1

Related Questions