.NET 帮助

C# 匿名对象(开发者如何使用)

发布 2025年一月14日
分享:

匿名对象的介绍

C# 中的匿名类型提供了一种机制,可以将公共只读属性封装到一个匿名类型对象中,而无需显式定义一个正式的类声明。 它对单对象结构很有用。 它们是由编译器生成的类型,直接继承自System.Object,能够有效封装对象属性,并作为轻量级、不可变的数据容器。 这些类型是密封类,编译器会自动推断并生成类型名,而在源代码级别无法访问。 我们还将发现IronPDF作为.NET项目的PDF库。

主要特点

  • 匿名类型在其功能上受到严格限制:
  • 属性在匿名类型的属性定义中自动实现为公共只读属性。
  • 用户无法在其中显式定义方法、事件或其他类成员,如equals和gethashcode方法。
  • 无法使用空值、匿名函数或指针类型进行初始化,以确保匿名类型的完整性。

常见用例

LINQ 操作

匿名数据类型对象在 LINQ 查询表达式中表现出色,尤其是在用于匿名类型对象的 select 子句中,在这些子句中,它们可以高效地从较大对象中返回特定属性子集。 这种方法通过创建仅包含必要数据的临时对象来优化内存使用。

临时数据分组

它们作为高效的容器,用于临时数据结构,当创建正式类显得多余时非常适合。这对于短期数据转换或中间计算特别有用。

属性封装

匿名数据类型通过只读属性提供了一种整洁的方法,将相关对象属性捆绑在一起。 编译器在确保类型安全的同时,保持了简洁的属性访问语法。

语法和结构

匿名类型的创建遵循特定的模式,使用var关键字以及new运算符和对象初始化语法。 编译器自动生成一个在源代码级别无法访问的类型名称。

var person = new { FirstName = "Iron", LastName = "Dev", Age = 35 }; // public int age in this anonymous type
var person = new { FirstName = "Iron", LastName = "Dev", Age = 35 }; // public int age in this anonymous type
Private person = New With {
	Key .FirstName = "Iron",
	Key .LastName = "Dev",
	Key .Age = 35
}
VB   C#

属性初始化规则

编译器对匿名类型的属性初始化实施严格规则。所有属性必须在对象创建时初始化,不能被赋予空值或指针类型。一旦初始化,匿名类型属性的属性值可以使用标准的点表示法访问,但由于它们的只读特性,初始化后不能被修改。

类型推断和匹配

var person1 = new { Name = "Iron", Age = 30 };
var person2 = new { Name = "Dev", Age = 25 };
var person1 = new { Name = "Iron", Age = 30 };
var person2 = new { Name = "Dev", Age = 25 };
Dim person1 = New With {
	Key .Name = "Iron",
	Key .Age = 30
}
Dim person2 = New With {
	Key .Name = "Dev",
	Key .Age = 25
}
VB   C#

编译器为具有匹配的属性名称、类型和顺序的匿名类型生成相同的类型信息。 这允许在同一程序集内使用实例之间的类型兼容性在集合中或作为方法参数传递。

嵌套匿名类型

匿名数据类型支持具有匿名类型对象属性的复杂嵌套结构。 它有助于创建分层数据表示:

var student = new {
    Id = 1,
    PersonalInfo = new {
        Name = "James",
        Contact = new {
            Email = "james@email.com",
            Phone = "123-456-7890"
        }
    },
    Grades = new { Math = 95, Science = 88 }
};
var student = new {
    Id = 1,
    PersonalInfo = new {
        Name = "James",
        Contact = new {
            Email = "james@email.com",
            Phone = "123-456-7890"
        }
    },
    Grades = new { Math = 95, Science = 88 }
};
Dim student = New With {
	Key .Id = 1,
	Key .PersonalInfo = New With {
		Key .Name = "James",
		Key .Contact = New With {
			Key .Email = "james@email.com",
			Key .Phone = "123-456-7890"
		}
	},
	Key .Grades = New With {
		Key .Math = 95,
		Key .Science = 88
	}
}
VB   C#

集合操作

匿名类型在涉及集合操作和数据转换的场景中表现出色:

var items = new[] {
    new { ProductId = 1, Name = "Laptop", Price = 1200.00m },
    new { ProductId = 2, Name = "Mouse", Price = 25.99m },
    new { ProductId = 3, Name = "Keyboard", Price = 45.50m }
};
var items = new[] {
    new { ProductId = 1, Name = "Laptop", Price = 1200.00m },
    new { ProductId = 2, Name = "Mouse", Price = 25.99m },
    new { ProductId = 3, Name = "Keyboard", Price = 45.50m }
};
Dim items = {
	New With {
		Key .ProductId = 1,
		Key .Name = "Laptop",
		Key .Price = 1200.00D
	},
	New With {
		Key .ProductId = 2,
		Key .Name = "Mouse",
		Key .Price = 25.99D
	},
	New With {
		Key .ProductId = 3,
		Key .Name = "Keyboard",
		Key .Price = 45.50D
	}
}
VB   C#

IronPDF: C# PDF 库

IronPDF是一个强大的库,用于在.NET应用程序中生成、编辑和管理PDF文档。 在使用C#时,开发人员经常使用匿名对象来处理轻量级和临时的数据结构,尤其是在不需要创建整个类的情况下。 这些匿名对象可以无缝地与IronPDF一起使用以动态创建PDF文档. 它有助于创建灵活的解决方案,用于快速的数据到PDF工作流程。 以下是一个示例,说明IronPDF如何与匿名对象一起工作:

示例:使用匿名对象填充PDF

想象一下,您有一个销售数据列表,您想将其呈现为 PDF 中的表格。 与其创建一个正式的类,您可以使用匿名对象来快速格式化数据以进行渲染。

using IronPdf;
using System;
using System.Linq;
class Program
{
    static void Main()
    {
        License.LicenseKey = "Licenes-Key";
        // Sample data using anonymous objects
        var salesData = new[]
        {
            new { Product = "Laptop", Quantity = 2, Price = 1200.50 },
            new { Product = "Smartphone", Quantity = 5, Price = 800.00 },
            new { Product = "Headphones", Quantity = 10, Price = 150.75 }
        };
        // Create an HTML string dynamically using the anonymous object data
        var htmlContent = @"
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " +
            string.Join("", salesData.Select(item =>
                $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) +
            @"
            </tbody>
        </table>
        </body>
        </html>";
        // Generate the PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF
        pdf.SaveAs("SalesReport.pdf");
        Console.WriteLine("PDF generated successfully!");
    }
}
using IronPdf;
using System;
using System.Linq;
class Program
{
    static void Main()
    {
        License.LicenseKey = "Licenes-Key";
        // Sample data using anonymous objects
        var salesData = new[]
        {
            new { Product = "Laptop", Quantity = 2, Price = 1200.50 },
            new { Product = "Smartphone", Quantity = 5, Price = 800.00 },
            new { Product = "Headphones", Quantity = 10, Price = 150.75 }
        };
        // Create an HTML string dynamically using the anonymous object data
        var htmlContent = @"
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " +
            string.Join("", salesData.Select(item =>
                $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) +
            @"
            </tbody>
        </table>
        </body>
        </html>";
        // Generate the PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF
        pdf.SaveAs("SalesReport.pdf");
        Console.WriteLine("PDF generated successfully!");
    }
}
Imports IronPdf
Imports System
Imports System.Linq
Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "Licenes-Key"
		' Sample data using anonymous objects
		Dim salesData = {
			New With {
				Key .Product = "Laptop",
				Key .Quantity = 2,
				Key .Price = 1200.50
			},
			New With {
				Key .Product = "Smartphone",
				Key .Quantity = 5,
				Key .Price = 800.00
			},
			New With {
				Key .Product = "Headphones",
				Key .Quantity = 10,
				Key .Price = 150.75
			}
		}
		' Create an HTML string dynamically using the anonymous object data
		Dim htmlContent = "
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " & String.Join("", salesData.Select(Function(item) $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) & "
            </tbody>
        </table>
        </body>
        </html>"
		' Generate the PDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF
		pdf.SaveAs("SalesReport.pdf")
		Console.WriteLine("PDF generated successfully!")
	End Sub
End Class
VB   C#

C# 匿名对象(开发人员如何使用):图 1 - 上述代码示例的控制台输出

结论

C# 匿名对象(开发人员如何使用):图 2 - IronPDF 许可页面

C# 中的匿名类型提供了一种灵活且高效的方法来创建临时数据结构,而无需正式的类声明。 它们在处理 LINQ 查询、数据转换以及像 IronPDF 这样的库时特别有用。 将匿名类型与IronPDF的PDF生成功能相结合,为创建动态、数据驱动的PDF提供了一种强大的解决方案,同时代码开销最小化。

IronPDF 允许开发人员通过 a 进行功能测试免费试用,可轻松在您的 .NET 应用程序中探索其功能。 商业许可证起价为 $749,授予使用其全部功能集的权限,包括高性能的 HTML 到 PDF 渲染、PDF 编辑和安全功能。

下一步 >
C# 并行 Foreach(开发者如何使用)