C# Numele operatorului
Operatorul C# NameOf este folosit pentru a obține numele unei variabile, clase sau metode. Acesta returnează un șir simplu ca rezultat.
În codul predispus la erori, este util să capturați un nume de metodă, în care a apărut eroarea.
Îl putem folosi pentru înregistrare, validarea parametrilor, verificarea evenimentelor etc.
Notă: dacă dorim să obținem un nume complet calificat, putem folosi tipul de expresie împreună cu operatorul nameof.
Să vedem un exemplu care implementează numele operator.
C# Numele operatorului Exemplul 1
using System; namespace CSharpFeatures { class NameOfExample { public static void Main(string[] args) { string name = 'javatpoint'; // Accessing name of variable and method Console.WriteLine('Variable name is: '+nameof(name)); Console.WriteLine('Method name is: '+nameof(show)); } static void show() { // code statements } } } Ieșire:
Variable name is: name Method name is: show
De asemenea, îl putem folosi pentru a obține numele metodei în care a apărut excepția. Vezi următorul exemplu.
C# Numele operatorului Exemplul 2
using System; namespace CSharpFeatures { class NameOfExample { int[] arr = new int[5]; public static void Main(string[] args) { NameOfExample ex = new NameOfExample(); try { ex.show(ex.arr); } catch(Exception e) { Console.WriteLine(e.Message); // Displaying method name that throws the exception Console.WriteLine('Method name is: '+nameof(ex.show)); } } int show(int[] a) { a[6] = 12; return a[6]; } } } Ieșire:
Index was outside the bounds of the array. Method name is: show