C# 3.0

序言

自动实现的属性

匿名类型

查询表达式

Lambda 表达式

从 C# 3 开始,lambda 表达式提供了一种更简洁和富有表现力的方式来创建匿名函数。 使用 => 运算符构造 lambda 表达式:

Func<int, int, int> sum = (a, b) => a + b;
Console.WriteLine(sum(3, 4));  // output: 7

 

static List<int> GetSquaresOfPositiveByLambda(List<string> strList)
{
    return strList
        .Select(s => Int32.Parse(s)) // 转成整数
        .Where(i => i % 2 == 0) // 找出所有偶数
        .Select(i => i * i) // 算出每个数的平方
        .OrderBy(i => i) // 按照元素自身排序
        .ToList(); // 构造一个List
}
View Code

表达式树

扩展方法

定义

public static class ExtensionMethod
    {
        public static void ShowItems<T>(this IEnumerable<T> colletion)
        {
            foreach (var item in colletion)
            {
                if (item is string)
                {
                    Console.WriteLine(item);
                }

                else
                {
                    Console.WriteLine(item.ToString());
                }
            }
        }
    }
View Code

调用

"123123123123".ShowItems();//字符串
new[] { 1, 2, 3, 4, }.ShowItems();//int数组
new List<int> { 1, 2, 3, 4 }.ShowItems();//List容器
View Code

隐式类型本地变量

从 Visual C# 3.0 开始,在方法范围内声明的变量可以具有隐式“类型”var。 隐式类型本地变量为强类型,就像用户已经自行声明该类型,但编译器决定类型一样。 i 的以下两个声明在功能上是等效的:

var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.

分部方法

对象和集合初始值设定项

资料

posted @ 2019-12-08 12:12  ~沐风  阅读(329)  评论(0编辑  收藏  举报