C #6.0 (C # vNext): Nameof Expressions
The Nameof Expressions parameter is the expression for obtaining the name.
First look at the example:
Previous writing:
void Foo(Bar bar){ if (bar == null) { throw new ArgumentNullException("bar"); }}
New statement:
void Foo(Bar bar){ if (bar == null) { throw new ArgumentNullException(nameof(bar)); }}
In this way, you do not need to write the "bar" string. When we rename the bar, the program can also properly reflect the correct name.
Nameof can be used to obtain: Class Name, method name, parameter name, Attribute name.
Example:
Public class MyClass {[TestMethod] public static void Show (int age) {Console. writeLine (nameof (MyClass); // output the MyClass class name Console. writeLine (nameof (Show); // output the Show method name Console. writeLine (nameof (age); // output ageConsole. writeLine (nameof (testmethodattrieline) // output Attribute name }}
Another practical situation is as follows:
class Bar : INotifyPropertyChanged{ private int foo; public int Foo { get { return foo; } set { foo = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(Foo)); } } public event PropertyChangedEventHandler PropertyChanged;}
Use nameof (Foo) to replace the string "Foo ";