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 toTryDo.Since
MessageBox.Showdoesn’t return aDelegate, that won’t work.Instead, you should pass the
Showmethod itself, along with a parameter:Alternatively, you can pass an anonymous method that calls the function:
Note that your function will perform faster if you make generic overloads that take
Funcs andActions instead of taking aDelegateand callingDynamicInvoke.