vendredi 28 février 2020

Accessing function arguments (and their names) during an invocation?

I've got about 50 functions taking anywhere from 2 to 20 positional arguments (required interface for an Excel com add-in).

The all look something like this:

public static string ACustomFunction(string FirstArg, object Arg2, int ThirdArg, ...)
{
    try {
        if(IsErrorValue(FirstArg, out string errorDescription))
            return $"Error: {nameof(FirstArg)} was {errorDescription}";
        if(IsErrorValue(Arg2, out rrorDescription))
            return $"Error: {nameof(Arg2)} was {errorDescription}";
        if(IsErrorValue(ThirdArg, out errorDescription))
            return $"Error: {nameof(ThirdArg)} was {errorDescription}";
        // ... Do some real work
    }
    catch(Exception ex){
        return $"Good Excel formulas don't throw exceptions: {ex.Message}";
    }
}

It ends up generating a ton of error checking code for something fairly repetetive and formulaic.


I would much rather if I could start each function with something like:

if(AnyErrors(Reflection.CurrentMethodInvocation.Args, out errorMessage))
   return errorMessage;

And have some helper method (AnyErrors) loop over the arguments, and if any has an error, return the appropriate error message, including the name of the argument that had the error.


So far the best I can do is to exhaustively list out all arguments and their names for each function - but this feels fragile (prone to omissions when adding new arguments):

string anyErrors = AnyErrors(FirstArg, nameof(FirstArg), Arg2, nameof(Arg2), ThirdArg, nameof(ThirdArg), ...));
if(anyErrors != null)
   return anyErrors;

public static string AnyErrors(params object[] args)
{
   for (int i = 0; i < args.Length; i++)
      if(IsErrorValue(args[0], out string errorDescription))
         return $"Error: {nameof(args[1])} was {errorDescription}";
   return null;
}

Is this something I can do more elegantly, perhaps with some clever reflection? (Preferably something that doesn't carry a large performance penalty - Excel formulas are expected to be snappy).

Thanks





Aucun commentaire:

Enregistrer un commentaire