c# - C# .NET 匿名类型的真实示例

标签 c# .net

我正在学习 C# 中的匿名类型,我了解它们的定义和使用方式。下面是我为匿名类型尝试过的示例代码。

var myType = new {
Name = "Yasser",
City = "Mumbai"
};
Console.WriteLine("Name: {0}, Type: {1}", myType.Name, myType.City);

我的问题

在现实世界的场景中,这些会用在什么地方?谁能给我一个可以使用这些匿名类型的示例或场景。

最佳答案

LINQ 查询经常使用它们:

var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

{ prod.Color, prod.Price } 是一个匿名类型,具有只读的 ColorPrice 属性。如果您要遍历该查询的结果,您可以将该类型用作任何其他类:

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

换句话说,您不必定义一个看起来像这样的新类:

public class ColoredPricedItem
{
    public Color {get;}
    public Price {get;}
}

此外,ColorPrice 类型可以从您的查询中正确推断出来。

关于c# - C# .NET 匿名类型的真实示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11795046/

相关文章:

c# - WCF - WCF 客户端调用 WCF 服务时出现 'The service certificate is not provided for target' 错误

c# - 将 C# 代码转换为 C++ : Hex to Binary

c# - Service Fabric 应用程序中的静态变量范围

.net - 我应该使用哪个编程平台来使用具有 WS-Security 的 SOAP 服务?

c# - Wix .net 4 先决条件

c# - 将 MySqlDataReader 存储在变量中

c# - 在 C# 中从列表中检索最大元素索引的优雅方法

c++ - 错误 C2440 '=' : cannot convert from 'cli::array<Type> ^' to 'wchar_t'

c# - Windows 蓝牙 le GetGattServicesAsync 方法中的错误

.net - 使用 String.Format 进行数字格式化