English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In C#, un tipo anonimo è un tipo (classe) senza nome, il cui nome può contenere solo attributi di sola lettura pubblici. Non può contenere altri membri, come campi, metodi, eventi, ecc.
Creare un tipo anonimo utilizzando l'operatore new con la sintassi dell'inizializzatore di oggetto. Il variabile di tipo implicito var viene utilizzata per salvare il riferimento al tipo anonimo.
L'esempio seguente dimostra come creare una variabile di tipo anonimo student che contiene tre proprietà: Id, FirstName e LastName.
var student = new { Id = 1, FirstName = "James", LastName = "Bond" };
Le proprietà dei tipi anonimi sono di sola lettura e non possono essere inizializzate con null, funzioni anonime o tipi di puntatore. Puoi accedere a queste proprietà utilizzando il simbolo di punto (.), come per le proprietà degli oggetti. Ma non puoi modificare il valore delle proprietà perché sono di sola lettura.
var student = new { Id = 1, FirstName = "James", LastName = "Bond" }; Console.WriteLine(student.Id); //Output 1 Console.WriteLine(student.FirstName); //Output: James Console.WriteLine(student.LastName); //Output: Bond student.Id = 2;//Errore: impossibile modificare il valore student.FirstName = "Steve";//Errore: impossibile modificare il valore
Le proprietà di un tipo anonimo possono includere un altro tipo anonimo.
var student = new { Id = 1, FirstName = "James", LastName = "Bond", Address = new { Id = 1, City = "London", Country = "UK" } };
Puoi anche creare un array di tipi anonimi.
var students = new[] { new { Id = 1, FirstName = "James", LastName = "Bond" }, new { Id = 2, FirstName = "Steve", LastName = "Jobs" }, new { Id = 3, FirstName = "Bill", LastName = "Gates" } };
I tipi anonimi sono sempre locali per il metodo che li definisce. Non possono essere restituiti dal metodo. Tuttavia, i tipi anonimi possono essere passati come parametri di tipo oggetto a un metodo, ma non è consigliabile farlo. Se è necessario passarli a un altro metodo, utilizzare struct o class invece di un tipo anonimo.
Di solito, si utilizza l'operatore Select delle query LINQ per creare tipi anonimi, per restituire un sottoinsieme di attributi di ogni oggetto nella raccolta.
class Program { static void Main(string[] args) { IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", age = 18 } new Student() { StudentID = 2, StudentName = "Steve", age = 21 }, new Student() { StudentID = 3, StudentName = "Bill", age = 18 }, new Student() { StudentID = 4, StudentName = "Ram", age = 20 }, new Student() { StudentID = 5, StudentName = "Ron", age = 21 } }; var students = from s in studentList select new { Id = s.StudentID, Name = s.StudentName }; foreach(var stud in students) Console.WriteLine(stud.Id + "-" + stud.Name); {} {} public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int age { get; set; } {}
1-John 2-Steve 3-Bill 4-Ram 5-Ron
In the above example, the select clause of the LINQ query selects only the StudentID and StudentName properties and renames them to Id and Name respectively. Therefore, it is very useful in saving memory and unnecessary code. The query result set only contains the StudentID and StudentName properties, as shown in the following debug view.
Visual Studio supports IntelliSense for anonymous types as shown below.
All the anonymous types internally derive directly from the System.Object class. The compiler generates a class with some automatically generated names and applies the appropriate type to each property based on the value expression. Although your code cannot access it. You can view the name using the GetType() method.
static void Main(string[] args) { var student = new { Id = 1, FirstName = "James", LastName = "Bond" }; Console.WriteLine(student.GetType().ToString()); {}