天天看点

nameof()

01作用:运算符获取变量、类型或成员的名称作为字符串常量

Console.WriteLine(nameof(System.Console));//Console
  Console.WriteLine(nameof(List<int>)); //list
  Console.WriteLine(nameof(List<int>.Count));//Count      

02nameof 运算符在编译时进行求值,在运行时无效。

可以使用 nameof 运算符使参数检查代码更易于维护:

class Student
    {
        public static void Sum(string arg)
        {
            if (arg==null)
            {
                //当将空引用传递给不接受它作为有效参数的方法时引发的异常。
                throw new ArgumentNullException("arg");
            }
        }
    }      
class Student
    {
        public static void Sum(string arg)
        {
            if (arg==null)
            {
                //当将空引用传递给不接受它作为有效参数的方法时引发的异常。
                throw new ArgumentNullException(nameof(arg));
            }
        }
    }