时代的变化真是快,今天看
MVC
程序的时候在
Global.asax.cs
文件里看到
:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
What the...
new
{ controller = "Home", action = "Index", id = "" }
???
这是什么代码阿,一时大脑空白。
C#
的语法变成这样了,
又一次感悟到自己落后了,落后到连代码也看不明白了。
这是
.NET 3.0
里添加的
匿名类型
(Anonymous Types),
比如
:
var
a = new { controller = "Home", action = "Index", id = "" };
1.
这是
class types
2.
里面的属性只读
(read-only)
使用
Anonymous Types (
最常用在
LINQ
里
)
class
Customer {
public Customer(string s, int a) {
this.Name = s;
this.Age = a;
}
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
static void Main(string[] args) {
List<Customer> list = new List<Customer>();
Customer c = new Customer("A", 20);
list.Add(c);
c = new Customer("B", 21);
list.Add(c);
c = new Customer("C", 22);
list.Add(c);
c = new Customer("D", 23);
list.Add(c);
var query=from customer in list
where customer.Name!="B"
select new {Name=customer.Name,Age=customer.Age};
foreach(var q in query){
Console.WriteLine("Name is:"+q.Name+" Age is:"+q.Age);
}
}
}
更多信息请参考
:
http://msdn.microsoft.com/en-us/library/bb397696.aspx
http://blogs.msdn.com/charlie/archive/2007/09/26/choosing-not-to-use-anonymous-types-in-query-expressions.aspx
本文出自 “Xhinker” 博客,转载请与作者联系!