Convert delegation method?

I want to call for example TryDo.Do(MessageBox.Show(""), null);

How can i do this?

using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}
+3
source share
3 answers

Your code calls MessageBox.Show, then tries to pass the result to TryDo.
Since it MessageBox.Showdoes not return Delegate, this will not work.

Instead, you must pass the method Showyourself, as well as the parameter:

TryDo.Do(new Func<string, DialogResult>(MessageBox.Show), "");

Alternatively, you can pass an anonymous method that calls a function:

TryDo.Do(new Action(() => MessageBox.Show("")));

Please note that your function will work faster if you do general overloads that accept Funcand Actioninstead of accepting Delegateand invoking DynamicInvoke.

+3

:

Delegate d = (Action)delegate { MessageBox.Show(""); };
TryDo.Do(d, null);
+1

, MessageBox.Show("") - , ,

TryDo.Do(MessageBox.Show(""),null);

TryDo.Do MessageBox.Show.

You really need to pass a delegate that contains the method you are trying to call, because

TryDo.Do(MessageBox.Show,null);

will also fail with the error that the method cannot be passed as a delegate.
The easiest way to create a delegate from a method is to use delegates Func<..>and Action<...>general ones (Func for those methods that return something, an action for those that are invalid), for example:

var myDelegate = new Func<string, DialogResult>(MessageBox.Show);
TryDo.Do(myDelegate, null)
0
source

Source: https://habr.com/ru/post/1781247/


All Articles