Throwing ArgumentNullException

前端 未结 12 2202
名媛妹妹
名媛妹妹 2020-12-08 02:10

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it\'s a fatal error and an exception shoul

12条回答
  •  自闭症患者
    2020-12-08 02:16

    You can use syntax like the following to not just throw an ArgumentNullException but have that exception name the parameter as part of its error text as well. E.g.;

    void SomeMethod(SomeObject someObject)
    {
        Throw.IfArgNull(() => someObject);
        //... do more stuff
    }
    

    The class used to raise the exception is;

    public static class Throw
    {
        public static void IfArgNull(Expression> arg)
        {
            if (arg == null)
            {
                throw new ArgumentNullException(nameof(arg), "There is no expression with which to test the object's value.");
            }
    
            // get the variable name of the argument
            MemberExpression metaData = arg.Body as MemberExpression;
            if (metaData == null)
            {
                throw new ArgumentException("Unable to retrieve the name of the object being tested.", nameof(arg));
            }
    
            // can the data type be null at all
            string argName = metaData.Member.Name;
            Type type = typeof(T);
            if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
            {
                throw new ArgumentException("The expression does not specify a nullible type.", argName);
            }
    
            // get the value and check for null
            if (arg.Compile()() == null)
            {
                throw new ArgumentNullException(argName);
            }
        }
    }
    

提交回复
热议问题