I want to call for example TryDo.Do(MessageBox.Show(""), null);
how can I do that??
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; }
}
}
Your code calls MessageBox.Show, then tries to pass the result to TryDo.
Since MessageBox.Show doesn't return a Delegate, that won't work.
Instead, you should pass the Show method itself, along with a parameter:
TryDo.Do(new Func<string, DialogResult>(MessageBox.Show), "");
Alternatively, you can pass an anonymous method that calls the function:
TryDo.Do(new Action(() => MessageBox.Show("")));
Note that your function will perform faster if you make generic overloads that take Funcs and Actions instead of taking a Delegate and calling DynamicInvoke.
Try this:
Delegate d = (Action)delegate { MessageBox.Show(""); };
TryDo.Do(d, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With