C# 匿名类型

C# 中的匿名类型允许我们创建一种类型而不指定名称。例如:

var subject = new {Name = "Math", Code = 123};

在这里,subject 是一个匿名类型变量,包含两个属性:NameCode

您可以看到我们使用 new 运算符创建了一个匿名类型。


示例:C# 匿名类型

using System;
class Program
{
    static void Main()
    {
// create an anonymous type containing 3 properties var person = new { Age = 34, Name = "John", Address = "Miami" };
// display the anonymous type Console.WriteLine(person); } }

输出

{ Age = 34, Name = John, Address = Miami }

在上面的示例中,person 是一个匿名类型变量,具有属性:AgeNameAddress,分别具有值 32"John""Miami"


C# 嵌套匿名类型

在 C# 中,我们也可以在另一个匿名类型的属性中创建匿名类型。这称为嵌套匿名类型。例如:

using System;
class Program
{
    static void Main()
    {
        // create another anonymous type inside Employee property 
        var school = new
        {
            Address = "Orlando",
            Contact = 1200,
Employee = new { Id = 3, Name = "Tina" }
}; // access Address property Console.WriteLine(school.Address); // access Id property of Employee property Console.WriteLine(school.Employee.Id); } }

输出

Orlando
3

在上面的示例中,请注意代码

var school = new
{
    Address = "Orlando",
    Contact = 1200,
    Employee = new { Id = 3, Name = "Tina" }
};

在这里,我们创建了一个匿名类型变量 school,它具有属性:AddressContactEmployee。您可以看到 Employee 属性本身也是一个匿名类型。

这是嵌套匿名类型的示例。

此外,我们还使用点运算符来访问嵌套匿名类型的属性。

  • school.Address - 访问 school 的 Address 属性
  • school.Employee.Id - 访问 Id 属性,该属性存在于 Employee 属性中

C# 匿名类型的特性

C# 匿名类型的一些特性是:

  • 它封装了一组只读属性。
  • 它不能包含类的​​方法或事件。
  • 它具有局部范围。这意味着匿名类型仅在定义它的类中可访问。
  • 我们可以创建匿名类型的数组。
  • 我们可以使用 LINQ 检索匿名类型的特定属性。

常见问题

匿名类型可以包含方法吗?

不,匿名类型不能包含方法。例如:

using System;
class Program
{
    static void Main()
    {
        // create an anonymous type containing 3 properties 
        var person = new
        {
// throws error since we can't define a method // inside anonymous type static void MyMethod() { Console.WriteLine("..."); }
}; // display the anonymous type Console.WriteLine(person); } }

这将引发错误。

可以更改匿名类型中的属性吗?

不,我们不能更改匿名类型中的属性。更改属性的值会引发错误。例如:

using System;
class Program
{
    static void Main()
    {
        // create an anonymous type containing 3 properties 
        var person = new { Age = 34, Name = "John", Address = "Miami" };

// change the value of Age property person.Age = 36;
Console.WriteLine(person.Age); } }

错误:

Property or indexer '<anonymous type: int Age, string Name, string Address>.Age' cannot be assigned to -- it is read only
如何创建匿名类型的数组?

我们可以创建匿名类型的数组,如下所示:

using System;
class Program
{
    static void Main()
    {
// create an array of anonymous type var employee = new[] { new{ID = 1, Name = "Jack"}, new{ID = 2, Name = "Jim"}, };
// access second element of the employee array using index Console.WriteLine("Second element of employee array is: " + employee[1]); // access the Name property of second anonymous type Console.WriteLine("Name property of second anonymous type is: " + employee[1].Name); } }

输出

Second element of employee array is: { ID = 2, Name = Jim }
Name property of second anonymous type is: Jim

在上面的示例中,请注意代码,

// create an array of anonymous type 
var employee = new[]
{
    new{ID = 1, Name = "Jack"},
    new{ID = 2, Name = "Jim"},
};

在这里,我们使用 [] 创建了一个名为 employee 的数组。employee 数组包含匿名类型作为其元素。

这里,

  • employee[1] - 访问数组中位于索引 1 的元素
  • employee[1].employeeName - 访问第二个匿名类型的 employeeName 属性
如何在 LINQ 中检索匿名类型的特定属性?

我们可以在 LINQ 中使用匿名类型,它基本上从集合中的每个对象检索属性子集。例如:

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    // define a class that contains three members 
    class car
    {
        public int Model;
        public string Name;
        public int Rating;
    }
    static void Main()
    {
        // create a list of car type 
        List<car> carInfo = new List<car>(){
            new car(){Model = 43, Name = "BMW", Rating = 4},
            new car() {Model = 23, Name = "Suzuki", Rating = 3},
        };

// select specific properties from carInfo var result = from c in carInfo select new { c.Model, c.Name };
// iterate through every items of present in result foreach (var items in result) { Console.WriteLine(items.Model + "-" + items.Name); } } }

输出

43-BMW
23-Suzuki

在上面的示例中,carInfo 是一个列表,其对象包含匿名类型。请注意下面的代码:

List<car> carInfo = new List<car>(){
            new car(){Model = 43, Name = "BMW", Rating = 4},
            new car() {Model = 23, Name = "Suzuki", Rating = 3},
        };

您可以在下面的代码中看到,我们使用 select 子句从 carInfo 列表中选择了 ModelName 属性

// select specific properties from carInfo
var result = from c in carInfo
             select new { c.Model, c.Name };

此外,使用 foreach 迭代 result 变量会显示我们选择的特定属性。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战