发一些我写的C#3.0的新特性代码给大家看看,喜欢的可以学习学习:
1.可以使用弱类型了
var a = 1;
var b = "sikezx";
Console.WriteLine(a);
Console.WriteLine(b);
注意:
  1.在声明时必须同时赋值,因为声明依赖于赋值号右边的表达式,如果有下面的语句:
var integer;
integer = 10; 
  编译时会报Implicitly typed locals must be initialized错误。

  2.在使用var声明一个局部变量后,它仍然具有强类型,可以做如下测试:
var integer = 10;
integer = " edisundong "; 
  编译时会报Cannot implicitly convert type 'string' to 'int'错误。

  3. 初始化器表达式的编译期类型不可以是空(null)类型,编译器无法根据null来推断出局部变量的类型,如有下面的语句:
var integer = null; 
  编译时会报Cannot assign '<null>' to an implicitly typed local错误。

  4.初始化语句必须是一个表达式,初始化表达式不能包含它自身,但是可以是包含一个对象或集合初始化器的一个new表达式(即匿名类型)。
  如可以这样去声明:
var coll = new Hashtable(); 
  5. var的声明仅限于局部变量,也可以包含在foreach、for、using语句中。下面的使用是错误的:
class Program
{
 private var i = 10; //全局私有变量。
 static void Main(string[] args)
 { }
}
2.自动属性
声明属性的方法简化,,代码量变少了很多哈!
    public string name { get; set; }
    public int age { get; set; }
3.集合初始化
例如:
 public  class Class1
    {
        public string name { get; set; }
        public int age { get; set; }
        public Class1(int aa)
        {
            age = aa;
        }
 }

static void Main(string[] args)
        {
            Class1 cs = new Class1(55) { name = "sikezx", age = 33 };
            Console.WriteLine(cs.name + "  " + cs.age);
  }
注意:A.集合初始化可以和构造函数一起使用,也可以单独使用
      B.如一起使用,构造函数先执行
4.匿名类型(直接继承于Object)
      var a = new { name = "芒果", price = 15.5 };
      var b = new { name = "西瓜", price = 55.5 };
      a = b;
      Console.WriteLine(a.name + "  " + a.price);
5.扩展方法
public static class Class1
    {
      public static string say(this string name)
           {
            return string.Format("hello {0}",name);
           }
        public static string say(this int age)
           {
           return string.Format("age:{0}",age);
           }
    }
static void Main(string[] args)
        {
            string na = "sikezx";
            int yy = 44;
            string hi = na.say();
            var dd = yy.say();
            Console.WriteLine(hi);
            Console.WriteLine(dd);
  }
注意:扩展方法必须是静态类
6.查询表达式
static void Main(string[] args)
        {
            selelct();
        }
  
public static void selelct() {
        Dictionary<string,int> students=new Dictionary<string,int>();
            students.Add("sikezx",24);
            students.Add("gj",21);
            students.Add("mj",22);
            IEnumerable<KeyValuePair<string, int>> qu = from student in students
                                                        where student.Value <= 23
                                                        orderby student.Value descending
                                                        select student;
            foreach (var student in qu) {
                Console.WriteLine(student.Key + "  " + student.Value);
            }
            Console.ReadLine();
       
        }

以上仅仅是我最近学习的一些东西,代码是在vs2008上写的,如果有兴趣的可以和我讨论,呵呵!互相学习!

posted on 2008-05-03 20:49  sikezx.net  阅读(196)  评论(0编辑  收藏  举报