新增的语法确实解决了很多问题,方便的很多。总结一下,防止日后时间长忘记。 

  1.隐式类型化本地变量、隐式类型数组初始化

/*
* 1.1本地化类型隐藏
* 1.2隐式类型数组初始化
*/
/// <summary>
///
/// </summary>
public void HideType()
{
var i
= 10;
var s
= "abc";
// 隐式类型数组
var list = new[] {1, 2, 3, 4};
UseSet(list);
var listEntity
= new[]
{
new {Id = 1, Name = "Yang"},
new {Id = 1, Name = "Che"}
};
UseSet(listEntity);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
private void UseSet<T>(IEnumerable<T> list)
{
foreach(var item in list)
{
Console.Write(item
+ "\t");
}
}

  2.对象初始化器、集合初始化器

/*
* 2.对象初始化器
* 3.集合初始化器
*/
/// <summary>
///
/// </summary>
public void ClassInitialization()
{
var entity
= new Entity {Id = 1, Name = "Yang"};

var list
= new List<Entity>
{
new Entity {Id = 1, Name = "Yang"},
new Entity {Id = 2, Name = "Che"}
};
foreach (var item in list)
{

}
}

  3.匿名类型 

/*
* 4.匿名类型
*/
/// <summary>
///
/// </summary>
[Test]
public void AnonymousTypes()
{
var anonymous1
= new { Id = 10, Name = "Yang" };
var anonymous2
= new { anonymous1, a = 10 };
Test(anonymous1);
Test(anonymous2);
}
/// <summary>
/// 4 匿名类型调用
/// </summary>
/// <param name="item"></param>
private void Test(object entity)
{
foreach(var item in entity.GetType().GetProperties())
{

}
}

  4.扩展方法 



[Test]
public void Expand()
{
var i
= 10;
var entity
= new Entity
{
Id
= 1, Name = "Yang"
};
var name
= entity.GetFullName();
}
/// <summary>
/// 扩展方法
/// </summary>
static class Expand
{
public static string GetFullName(this Entity entity)
{
return entity.ToString();
}
}

  5.委托、匿名方法、Lambda表达式

using NUnit.Framework;

namespace NewFeatures
{
internal delegate int MyDelegate(int i, int j);
[TestFixture]
public class Delegate
{
[Test]
public void Main()
{
// 委托函数
MyDelegate myDel = Function;
// lambda表达式
myDel += (x, y) => { return Function(x, y); };
var value
= myDel(10, 20);
}

private int Function(int i, int j)
{
return i + j;
}
}

[TestFixture]
public class AnonymousFunction
{
[Test]
public void Main()
{
// 匿名方法
MyDelegate myDel = delegate(int i, int j)
{
int a = i * j;

return a;
};

myDel(
10, 20);
}
}
}

  当然还有Lambda表达式,和Linq语言。

所有的这些新增的特性,统一的展现都是在Linq语言当中。都是为其进行服务的。

事例:下载地址