Getting the extension name of the called party

I created a simple class ArgumentValidatorto simplify the prerequisites of the argument in any given method. Most of them are nulleither limitations, and it becomes quite tedious after a couple

if (arg == null ) throw new ArgumentNullException(nameof(arg));

So, I came up with the following setup:

public static class ArgumentValidator
{
    public interface IArgument<T>
    {
        string ParamName { get; }
        T Value { get; }
    }

    private class Argument<T>: IArgument<T>
    {
        public Argument(T argument, string paramName)
        {
            ParamName = paramName;
            Value = argument;
        }

        public string ParamName { get; }
        public T Value { get; }
    }

    public static IArgument<T> Validate<T>(this T argument, string paramName = null)
    {
        return new Argument<T>(argument, paramName ?? string.Empty);
    }

    public static IArgument<T> IsNotNull<T>(this IArgument<T> o)
    {
        if (ReferenceEquals(o.Value, null))
            throw new ArgumentNullException(o.ParamName);

        return o;
    }

    public static IArgument<T> IsSmallerThan<T, Q>(this IArgument<T> o, Q upperBound) where T : IComparable<Q> { ... }

    //etc.
}

And I can use it as follows:

public Bar Foo(object flob)
{
     flob.Validate(nameof(flob)).IsNotNull().IsSmallerThan(flob.MaxValue);
}

Ideally, I would like to get rid of nameof(flob)the call Validateand eventually get rid of Validatealltogether; the sole purpose Validateis to not skip the nameof(...)circuit every time you check.

Is there a way to get the name flobinside the method Validate()?

+4
source share
1 answer

. , LINQ ( devdigital answer here):

public static T Validate<T>(this Expression<Func<T>> argument)
{
    var lambda = (LambdaExpression)argument;

    MemberExpression memberExpression;
    if (lambda.Body is UnaryExpression)
    {
        var unaryExpression = (UnaryExpression)lambda.Body;
        memberExpression = (MemberExpression)unaryExpression.Operand;
    }
    else
    {
        memberExpression = (MemberExpression)lambda.Body;
    }

    string name = memberExpression.Member.Name;

    Delegate d = lambda.Compile();

    return (T)d.DynamicInvoke();
}

name - , :

MyMethods.Validate(() => o);

Validate T, . , , .

, :

Expression<Func<object>> f = () => o; // replace 'object' with your own type

f.Validate();
+3

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


All Articles