.NET 幫助

C# 匿名物件(開發者如何使用)

發佈 2025年1月14日
分享:

匿名物件的介紹

C# 中的匿名型別提供了一種機制,可以將公共唯讀屬性封裝到一個匿名型別物件中,而無需明確定義正式的類別聲明。 它對於單一物件結構很有用。 它們是編譯器生成的類型,直接繼承自 System.Object,有效封裝對象屬性,並作為輕量級、不可變的數據容器使用。 這些類型是密封類別,編譯器會自動推斷並生成類型名稱,該名稱在源代碼級別上不可訪問。 我們還將發現IronPDF作為 .NET 專案的 PDF 庫。

主要特點

  • 匿名類型在其功能上嚴格受限:
  • 在匿名類型的屬性定義中,屬性會自動實作為公共唯讀屬性。
  • 用戶無法在其中明確定義方法、事件或其他類成員,如 equals 和 gethashcode 方法。
  • 不能以空值、匿名函數或指標類型初始化,以確保匿名類型的完整性。

常見用例

LINQ 操作

匿名物件在 LINQ 查詢表達式中表現出色,尤其是在選擇子句中針對匿名類型物件的情況下,可以有效地從較大的物件中返回特定屬性子集。 這種方法透過創建僅包含必要數據的臨時對象來優化記憶體使用率。

暫時性資料分組

它們在創建正式類別過於繁瑣時,充當臨時數據結構的有效容器。這對於短期數據轉換或中間計算特別有用。

屬性封裝

匿名資料類型提供了一種簡潔的方法,使用唯讀屬性將相關的物件屬性捆綁在一起。 編譯器在確保類型安全的同時,維持屬性存取的簡潔語法。

語法和結構

匿名類型的創建遵循特定的模式,使用 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 允許開發人員通過一個試用功能來測試其特點免費試用,使您可以輕鬆在您的 .NET 應用程式中探索其功能。 商業授權起價為 $749,並授予訪問其完整功能集的權限,包括高效能的 HTML 到 PDF 渲染、PDF 編輯和安全功能。

下一個 >
C# 平行 Foreach(其如何運作對於開發者)