Get the original nameof(…) of a variable?

前端 未结 1 1393
北海茫月
北海茫月 2021-01-25 00:57

I have this

public static class Parameters
{
    public static void Required(this T parameter, string paramName) where T : class
    {
        if (param         


        
相关标签:
1条回答
  • 2021-01-25 01:57

    You could make the Requred-function accepting a Expression. And from the expression you can read out the name of the member name. It's descriped here.

        public static void Required<T>(Expression<Func<T>> parameter) where T : class
        {
            if (parameter.Compile().Invoke() == null)
            {
                var caller = ((MemberExpression)parameter.Body).Member.Name;
                throw new ArgumentNullException(caller);
            }
    
            // ...
        }
    

    and call it like this:

    Parameters.Required(() => settings);
    
    0 讨论(0)
提交回复
热议问题