C#3.0新增功能快速预览

来源:互联网 发布:淘宝的阿里旺旺打不开 编辑:程序博客网 时间:2024/04/29 09:10

1.通过var关键字实现灵活的类型声明:
class ImplicitlyTypedLocals2
{
    static void Main()
    {           
        string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

        // If a query produces a sequence of anonymous types,
        // then you must also use var in the foreach statement.
        var upperLowerWords =
             from w in words
             select new { Upper = w.ToUpper(), Lower = w.ToLower() };

        // Execute the query
        foreach (var ul in upperLowerWords)
        {
            Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
        }
    }       
}
2.更加灵活的对象构造方式:
private class Cat
{
    // Auto-implemented properties
    public int Age { get; set; }
    public string Name { get; set; }
}
static void MethodA()
{
    // Object initializer
    Cat cat = new Cat { Age = 10, Name = "Sylvester" };
}
3.集合装配的特殊方法:
IEnumerable<int> highScoresQuery =
    from score in scores
    where score > 80
    orderby score descending
    select score;
4.对已存在的类型定义进行方法扩展:
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }  
}
using ExtensionMethods;
string s = "Hello Extension Methods";
int i = s.WordCount();
5.隐式集合类型定义:
var v = new { Amount = 108, Message = "Hello" };
var productQuery =
    from prod in products
    select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

6.Lambda语法:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
7.查询语法:
class LowNums
{
    static void Main()
    {  
        // A simple data source.
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        // Create the query.
        // lowNums is an IEnumerable<int>
        var lowNums = from num in numbers
            where num < 5
            select num;

        // Execute the query.
        foreach (int i in lowNums)
        {
            Console.Write(i + " ");
        }
    }       
}
// Output: 4 1 3 2 0
8.智能简约的访问器声明:
class LightweightCustomer
{
    public double TotalPurchases { get; set; }
    public string Name { get; private set; } // read-only
    public int CustomerID { get; private set; } // read-only
}

LightweightCustomer obj = new LightweightCustomer();
obj.TotalPurchases = 1;
Console.WriteLine(obj.TotalPurchases.ToString());

9.支持借口,类,结构,方法,特性的partial声明:
partial class Earth : Planet, IRotate { }
partial class Earth : IRevolve { }
 [System.SerializableAttribute]
partial class Moon { }
[System.ObsoleteAttribute]
partial class Moon { }

原创粉丝点击