Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

c# - How can I pass several methods (with parameters) AS a parameter?

Suppose I have the following WCF code:

  try
  {
       ServiceClient proxy = new ServiceClient();
       proxy.ClientCredentials.UserName.UserName = "user";
       proxy.ClientCredentials.UserName.Password = "password";
       proxy.GetData(2);
       if (proxy.State = CommunicationState.Opened)
       {
           proxy.GetData("data");
       }
       proxy.Close();
  }
  catch (FaultException ex)
  {
      // handle the exception      
  }

And since I notice that the try...catch and other logic is repetitive, not to mention that setting up a WCF call is expensive, I want to send many "methods and parameters" to this function.

In essence pass GetData(2) and GetData("data") as a method array, and have the results return either asynchronously or synchronously.

How would I accomplish this?

I suppose I could have two 'ref' objects to handle the results[] and a shared lock to the results[]. However I'm not sure how to pass "methods with parameters" as a parameter to another function.

Perhaps another way of looking at this might be an array of function pointers, to the same function with different params.

Can anyone nudge me into the right way of doing this?

More info:

I am asking this question so I can optimize this approach to handling WCF exceptions and retries but so I don't have to always open/close the client after each call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use delegates and pass them in a list.

The C# Func<T> delegate is used when a return value is needed.

List<Func<Data>> funcList = new List<Func<Data>>();
funcList.Add( () => GetData(2) );

// You can use any condition as you otherwise would to add to the list.
if (proxy.State = CommunicationState.Opened)
{
   funcList.Add( () => GetData("data") );
}

List<Data> ProcessFuncs(List<Func<Data>> funcDatas)
{
    List<Data> returnList = new List<Data>();
    foreach(var func in funcDatas)
    {
        returnList.Add(func());
    }
}

( as long as the return types are identical, this will work )

This is just an example of course; if your methods don't return anything, you can use the C# Action delegate, which just executes an action and doesn't return any value.

List<Action> actionList = new List<Action>();
actionList.Add( () => ProcessData("data")); // ProcessData is a void with no return type
actionList.Add( () => ProcessData(2));

public void ProcessActions(List<Action> actions)
{
    foreach(var action in actions)
    {
        action();
    }
}

In response to some comments:

This code compiles and is all equivalent:

class Program
{
    public static string GetData(string item) { return item; }
    public static string GetData(int item) { return item.ToString(); }

    static void Main(string[] args)
    {
        string someLocalVar = "what is it?";
        int someLocalValueType = 3;

        Func<string> test = () =>
        {
            return GetData(someLocalVar);
        };

        Func<string> test2 = () => GetData(someLocalValueType);
        someLocalValueType = 5;

        List<Func<string>> testList = new List<Func<string>>();

        testList.Add(() => GetData(someLocalVar));
        testList.Add(() => GetData(2));
        testList.Add(test);
        testList.Add(test2);

        someLocalVar = "something else";

        foreach(var func in testList)
        {
            Console.WriteLine(func());
        }

        Console.ReadKey();
    }
}

Result is:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...