我正在学习C#中的匿名类型,我已经理解了它们是如何定义和使用的。以下是我尝试过的一个匿名类型示例代码。
var myType = new {
Name = "Yasser",
City = "Mumbai"
};
Console.WriteLine("Name: {0}, Type: {1}", myType.Name, myType.City);
我的问题
在现实世界的哪些情境下,这些匿名类型会被使用?有人可以给我一个例子或场景,展示匿名类型可能被使用的情况吗?
我正在学习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 }
是一个匿名类型,它具有只读的 Color
和 Price
属性。如果您遍历该查询的结果,可以将该类型用作任何其他类:
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
换句话说,你不必定义一个新类,看起来像这样:public class ColoredPricedItem
{
public Color {get;}
public Price {get;}
}
此外,颜色
和价格
类型将从您的查询中正确推断出。
class User
{
public int ID;
public string FirstName;
public string LastName;
public int Age;
public string City;
public string Country;
}
你要创建一个T是用户类的通用列表。你创建了n个用户。 重点是,您不想在某些查询中显示所有字段(或属性),而只想显示人的名字和姓氏(作为一个整体)以及该人居住的城市。 因此,您在Linq中使用了一个新关键字(我将展示如何使用Linq的don符号):
List<User> users = new List<User>();
users.Add(new User { ID = 1, FirstName = "first 1", LastName = "last 1", Age = 32, City = "City 1", Country = "Country 1" });
users.Add(new User { ID = 2, FirstName = "first 2", LastName = "last 2", Age = 33, City = "City 2", Country = "Country 2" });
users.Add(new User { ID = 3, FirstName = "first 3", LastName = "last 3", Age = 34, City = "City 3", Country = "Country 3" });
var query = users.Select(s => new
{
FIRST_LAST = string.Format("{0} {1}", s.FirstName, s.LastName),
LIVING_IN = s.City
}).ToList();
foreach (var person in query)
{
string name = person.FIRST_LAST;
string city = person.LIVING_IN;
}
除了在Linq中使用外,它们还被asp.net MVC应用程序在Global.asax.cs中用于映射路由。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
var t = new Table(new { align="left", bgcolor="red", cellpadding="2" });
匿名类型是在C# 3中为LINQ添加的。当您只想从数据库中获取几个属性时,它们非常有用,例如http://msdn.microsoft.com/en-us/library/bb397696.aspx:
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
这将仅从数据库中获取颜色和价格两列 :)
你可以使用它来生成HTML元素。
以下示例使用方法"el"来生成具有给定属性和innerHTML的HTML元素。参数"params object[] objects"允许提供任意数量的匿名对象来定义所需的HTML属性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace anonymousTypes
{
class Program
{
static void Main(string[] args)
{
el("td", null, new { colspan = 36 }, new { style = "text-align: center;" });
Console.Read();
}
static string el(string tagName, string innerHTML, params object[] objects)
{
StringBuilder b = new StringBuilder();
b.Append("<").Append(tagName);
foreach (object obj in objects)
{
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
Console.Write(propertyInfo.Name + " | " + propertyInfo.GetValue(obj, null) + "\n");
}
}
b.Append(">");
if (innerHTML != null)
b.Append(innerHTML);
b.Append("</").Append(tagName).Append(">");
return b.ToString();
}
}
}