W
W
Wasya UK2018-09-08 16:37:12
C++ / C#
Wasya UK, 2018-09-08 16:37:12

How to pass a function in c#?

I'm trying to pass a function, I don't understand a little how to do this correctly:

namespace coordinates
{
    class Example
    {
        public string name;
        public Delegate mainFunc;

        public Example(string name, Delegate callback)
        {
            this.name = name;
            this.mainFunc = callback;
        }

        public void init()
        {
            this.mainFunc();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
VoidVolker, 2018-09-08
@VoidVolker

namespace coordinates
{
    class Example
    {
        public string Name;
        public Action MainFunc;

        public Example(string name, Action callback)
        {
            Name = name;
            MainFunc = callback;
        }

        public void Init()
        {
            MainFunc?.Invoke();
        }
    }
}

var r = new Example("Example name", () => Console.WriteLine("Example MainFunc"));

B
basrach, 2018-09-08
@basrach

Delegate(capitalized) is a static class that contains methods for working with delegates. The delegate itself must be declared through the delegate keyword (with a small letter), as a class or interface. For example: In this case, you can only use a specific delegate type, just like you use a specific one , etc., and not the class keyword itself. In the example above, the delegate type would be . To pass a function reference using a delegate, the signatures of the function and the delegate must match exactly. In the case of the above example , the function must also return and accept . In your case, the delegate type should be: You can assign a reference to your method to this delegate .
But there is no need to declare a delegate type in this case. In Net. Framework already has a number of delegates, just for such purposes. This Funcand Action.
You can just replace the word Delegatewith Actionin your code and it should work.

S
Station 72, 2018-09-09
@cjstress

using System;

namespace TOSTER
{
    class Program
    {
        static void Main(string[] args)
        {
            var example = new Example("example 1", () => { return "Result"; });
            var result = example.init();
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

    class Example
    {
        private readonly string _name;
        private readonly Func<string> _del;

        public Example(string name, Func<string> callback)
        {
            _name = name;
            _del = callback;
        }

        public string init()
        {
            return _del.Invoke();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question