C#3.0的新特性

/*
 *============================主要演示C#3.0的新特性=====================
 *一、自动属性
 *二、对像和集合初始化器
 *三、扩展方法
 *四、Lambda表达式
 * 13/6/2010 Berlin
 * 
 */
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqTest
{

    //演示自动属性
    public class Point
    {
        public int X { get; set; }//自动化属性

        public int Y { get; private set; }//带修饰符的自动化属性

        public int T { get; set; }
    }


    //演示对像和集合初始化器;
    class Test_45
    {
        Point p = new Point { X = 23, T =2};//可以通这种方式来实例化一个对像

        //初始化一个集合
        List<Point> PoList = new List<Point> 
                                     {
                                        new Point {X =2,T =3},
                                        new Point {X =4,T=2},
                                        new Point {X=23,T =90}
                                     };
        
    }


    //演示扩展方法,所谓扩展方法是指在C#3.0中,对于已经编译的程序集,在不需要重新编译源有代码或不公开源代码的程序集中添加相关方法
    //点评,对于调用 第三方API,在没有源代码的情况下想扩展相关功能,就用它啦
    //实现:用一个静态类,静态方法的第一个参数中传入要扩展的类名形如:this class object

    static class ExtensionsFunction
    {
        //对Point 扩展了一个方法GetZeroPoint
        public static  Point GetZeroPoint(this Point p)
        {
            return new Point { X = 0, T = 0 };
        }

        //对类Test_45扩展了一个显示自已类全名的方法
        public static void ShowSelfInfo(this Test_45 obj)
        {
            Console.WriteLine(obj.GetType().Assembly.FullName);
        }
    }


    //使用扩展方法
    public class TestExtension
    {
        public void TestExtenSionFuntion()
        {
            Point p = new Point { X = 8,T = 9 };
            Test_45 t = new Test_45();

            p.GetZeroPoint();//调用了Point的一个扩展方法,注意这个方法在类Point中是没有的

            t.ShowSelfInfo();
           
        }
        
    }

    //演示Lambda表达式
    //Lambda表达式是一种简化的匿名方法
    //有如下几种表现形式
    // (int x)=>{return x+1;}
    //(int x)=>x+1;
    //x=>x+1;
    //(x,y)=>x+y;
    public class LambdaTest
    {
        public void TestLambda()
        {
            List<Point> pList = new List<Point> 
                                        {
                                            new Point {X =2,T =3},
                                            new Point {X =4,T=1}
                                        };

            List<Point> ppList = new List<Point>();
            ppList = pList.FindAll(p => p.X > 2 && p.T < 3);
        }


    }
}

转载于:https://www.cnblogs.com/berlin/archive/2010/06/17/1759769.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值