LinqToSql--预备知识
1.隐含类型局部变量
例子:
protected void Page_Load(object sender, EventArgs e) { var str = "this is a string"; Display(str.GetType()); var integer = 100; Display(integer.GetType()); var array = new int[] { 1, 2, 3, 4, 5 }; Display(array.GetType()); var DefineArray = new DefineClass[] { new DefineClass(), new DefineClass(), new DefineClass() }; Display(DefineArray.GetType()); }
var只能用于局部变量,而不能用于字段.
2.匿名类型
允许开发人员定义行内类型,无虚显示定义类型,常与var配合使用,var用于声明匿名类型
例子:
protected void Page_Load(object sender, EventArgs e) { var user = new { name = "www", password = "111" }; Response.Write(user.name+"<br/>"); Response.Write(user.password + "<br/>"); Response.Write(user.GetType().ToString() + "<br/>"); }
结果:
3.扩展方法
static class DefineClassHelper { public static string GetTypeString(this DefineClass dc) { return dc.GetType().ToString(); } } class DefineClass { } public partial class linq_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DefineClass dc = new DefineClass(); Response.Write(dc.GetTypeString()); } }
DefineClass并没有定义GetTypeString方法,但是,定义了一个DefineClass的静态类,为该类提供了一个方法.
4.自动属性
例子:
class DefineClass { public string name { get; set; } public int age { get; private set; } }对于上例的age属性,只能获取,而不能再类的外部对该属性进行赋值.
5.对象初始化器
例子:
public class Person { public string name; public string password; }
对于这个类,可以使用如下方法进行初始化:
protected void Page_Load(object sender, EventArgs e) { Person p = new Person() { name = "www", password = "111" }; }
也可以进行如下初始化:
Person p = new Person { name = "www", password = "111" };
即:去掉括号也可以.
但是如果类定义如下,则不能进行这样的初始化:
public class Person { public string name; public string password; public Person(string name,string password) { this.name = name; this.password = password; } }
即:该类并没有默认的构造函数时,会报错.
6.集合初始化器
例子:
public partial class linq_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { IList<Person> list = new List<Person>{ new Person(){name="www",password="111"}, new Person(){name="zzz",password="222"} }; foreach (Person p in list) { Response.Write(p.ToString()); } } } public class Person { public string name; public string password; public override string ToString() { return this.name+"--"+this.password+"<br/>"; } }
结果:
7.Lambda表达式
例子:
protected void Page_Load(object sender, EventArgs e) { int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 6, 7, 8, 9 }; var result = from a in arr select a; foreach (var r in result) { Response.Write(r.ToString()+"<br/>"); } }
效果: