vendredi 15 janvier 2021

In C#, Can I somehow get the name of a method's first parameter (possibly with reflection)? [duplicate]

I have the following method:

private void VerifyInterval(int refreshInterval, int minimum, string fieldName)
{
    if (refreshInterval < minimum)
    {
        throw new ValidationException(new[] { new ValidationFailure(
            nameof(SalesforceDataRequestParameters.IncrementalRefreshIntervalInMinutes),
            $"When included, {fieldName} must be at least {minimum}."
        ) });
    }
}

I am calling it like this:

public Task<SalesforceDataRequestResult> RequestAdditionalSalesforceData(SalesforceDataRequestParameters request)
{
    _oAuthScopeValidator.VerifyUserHasAnyAcceptedScope(new string[] { _scopesConfig.AdminScopeName }, "to request additional data from Salesforce");
    VerifyInterval(request.IncrementalRefreshIntervalInMinutes, 5, nameof(SalesforceDataRequestParameters.IncrementalRefreshIntervalInMinutes));
    VerifyInterval(request.FullRefreshIntervalInDays, 1, nameof(SalesforceDataRequestParameters.FullRefreshIntervalInDays));
    VerifyInterval(request.RetentionAfterLastSyncInDays, 1, nameof(SalesforceDataRequestParameters.RetentionAfterLastSyncInDays));

    return _sObjectRequestManager.ProcessRequestAsync(request);
}

As you should see reading the code, the third parameter is redundant, as it is just sending in a string of the name of a field on SalesforceDataRequestParameters, the same field whose value has been sent into the method.

Is there a better way to do this, reducing the method to two parameters?

Alternatively, if I can't remove the third parameter, is there some way I can at least move the nameof() function into the method rather than call it repeatedly in the code?





Aucun commentaire:

Enregistrer un commentaire