C#3.0新特性小结(2)
2009-03-22 19:10 chenkai 阅读(384) 评论(0) 编辑 收藏 举报c#3.0中除了自动属性外,还添加:
代码演示实例:
//测试数组
public static void TestArray()
{
//测试数组
var intArray = new[] { 120, 110, 119 };
var strArray = new[] { "TreeyLee", "JFlyZhao", "JFlyingchen" };
var objArray = new[] {
//初始化对象
new {username="马鹏飞",userpass="AdminDoucment"},
new {username="周静",userpass="周界"}
};
//对单个变量赋值
var seta =intArray[0];
var setb = strArray[1];
var setc = objArray[1].userpass;//可以副单个属性 也可副单个对象objArray[0]
//打印当前数据
Console.WriteLine("seta:" + seta + "\nsetb:" +setb+ "\nsetc:" + setc);
}
/// <summary>
/// 综合测试匿名类型
/// </summary>
public class TotalTestAnnoy
{
//定义属性
public string username { get; set; }
public string userpass { get; set; }
public int age { get; set; }
//定义测试方法
public static void TestMethods()
{
//集合初始化器
List<TotalTestAnnoy> TotalList = new List<TotalTestAnnoy> {
//不能直接写new {
} 集合器中只能装TotalTestAnnoy对象,不能var类型
new TotalTestAnnoy{username="老顾",userpass="laogu",age=21},
new TotalTestAnnoy{username="周静",userpass="zhoujing",age=26},
new TotalTestAnnoy{username="陈凯",userpass="chenkai",age=21}
};
//定义匿名类型
var GetTotalList = from newtotallist in TotalList
where newtotallist.age == 21//吧结果定义成一个新对象 只包含两个属性newname 和newpass
select new { newname = newtotallist.username, newpass = newtotallist.userpass };
//循环打印新对象
foreach(var getfirst in GetTotalList)
{
//打印新实例结果
Console.WriteLine("定义新实例newname:"+getfirst.newname+"\nnewpass:\n"+getfirst.newpass);
}
}
}
public static void TestArray()
{
//测试数组
var intArray = new[] { 120, 110, 119 };
var strArray = new[] { "TreeyLee", "JFlyZhao", "JFlyingchen" };
var objArray = new[] {
//初始化对象
new {username="马鹏飞",userpass="AdminDoucment"},
new {username="周静",userpass="周界"}
};
//对单个变量赋值
var seta =intArray[0];
var setb = strArray[1];
var setc = objArray[1].userpass;//可以副单个属性 也可副单个对象objArray[0]
//打印当前数据
Console.WriteLine("seta:" + seta + "\nsetb:" +setb+ "\nsetc:" + setc);
}
/// <summary>
/// 综合测试匿名类型
/// </summary>
public class TotalTestAnnoy
{
//定义属性
public string username { get; set; }
public string userpass { get; set; }
public int age { get; set; }
//定义测试方法
public static void TestMethods()
{
//集合初始化器
List<TotalTestAnnoy> TotalList = new List<TotalTestAnnoy> {
//不能直接写new {
![](https://www.cnblogs.com/Images/dot.gif)
new TotalTestAnnoy{username="老顾",userpass="laogu",age=21},
new TotalTestAnnoy{username="周静",userpass="zhoujing",age=26},
new TotalTestAnnoy{username="陈凯",userpass="chenkai",age=21}
};
//定义匿名类型
var GetTotalList = from newtotallist in TotalList
where newtotallist.age == 21//吧结果定义成一个新对象 只包含两个属性newname 和newpass
select new { newname = newtotallist.username, newpass = newtotallist.userpass };
//循环打印新对象
foreach(var getfirst in GetTotalList)
{
//打印新实例结果
Console.WriteLine("定义新实例newname:"+getfirst.newname+"\nnewpass:\n"+getfirst.newpass);
}
}
}