📅  最后修改于: 2020-11-01 03:02:19             🧑  作者: Mango
C#匿名类型使我们可以创建具有只读属性的对象。匿名对象是没有显式类型的对象。 C#编译器生成类型名称,并且仅可用于当前代码块。
要创建匿名类型,我们必须将new运算符与对象初始化程序一起使用。
using System;
namespace CSharpFeatures
{
class AnonymousTypesExample
{
public static void Main()
{
// Creating Anonymous Object
var student = new { ID = 101, Name = "Peter", Email = "peter@example.com"};
// Accessing object properties
Console.WriteLine(student.ID);
Console.WriteLine(student.Name);
Console.WriteLine(student.Email);
}
}
}
输出:
101
Peter
peter@example.com
我们还可以在查询表达式中使用它来选择记录。在以下示例中,我们通过创建匿名类型来选择学生记录。
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class AnonymousTypesExample
{
public static void Main()
{
List students = new List {
new Student{ ID=101, Name="Rahul", Email="rahul@example.com" },
new Student{ ID=102, Name="Peter", Email="peter@abc.com" },
new Student{ ID=103, Name="Irfan", Email="irfan@example.com" }
};
var stquery =
from student in students
select new { student.ID, student.Name, student.Email }; // Creating Anonymous Types
foreach (var st in stquery)
{
Console.WriteLine("ID = {0}, Name = {1}, Email = {2}", st.ID, st.Name, st.Email);
}
}
}
}
输出:
ID = 101, Name = Rahul, Email = rahul@example.com
ID = 102, Name = Peter, Email = peter@abc.com
ID = 103, Name = Irfan, Email = irfan@example.com