A
A
Anton Fedoryan2016-01-17 18:55:32
C++ / C#
Anton Fedoryan, 2016-01-17 18:55:32

How to pass a function (method) as a parameter to a constructor?

Somewhere on the server side there is a function:

class RemoteServer
    {
        public int Value(string key)
        {
            return 1;
        }
    }

And there is a client application that will call this function. It must be written once in the class constructor.
class Client
    {
        public Client(тут нужно указать функцию Value) // Возможно еще какие-то параметры будут
        {
            // ...
        }

        public int UseFuncClient()
        {
            // А здесь нужно будет как-то использовать указанную функцию.
        }
    }

I'm guessing you need to use a delegate Func<>, but I can figure out how to do it the right way.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-01-17
@AnnTHony

private Func<string, int> fn;
public Client(Func<string, int> fn)
{
    this.fn = fn;
}

public int UseFuncClient()
{
    fn("text");
}

var rs = new RemoteServer();
var cl = new Client(rs.Value);

K
Ko1, 2016-01-17
@Ko1

public Client(Func<type1, type2 ... > method), something like this
, specifically in your case
public Client(Func<int, string> method)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question