自言自语

I'm Wang Xianyuan, writing for myself, more studying, more experience…

记 C# 3.0 的一些新特性

By

C# 3.0 的新特性还是比较多的,下面选几处记下。

自动属性(Auto-Implemented Properties)
在 .net2.0 下,写一个User类如下。

public class User
{
    private int _id;
    private string _name;
    private int _age;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

.net 3.0 的“自动属性”特性允许这样定义User类。

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

顾名思义,一部分代码有系统“自动化”实现了。

隐含类型局部变量(Local Variable Type Inference)与匿名类型(Anonymous Types)

var i = 5;//int
var j = 23.56;//double
var k = "C Sharp";//string
var x;//错误
var y = null;//错误
var z = { 1, 2, 3 };//错误

//匿名类型
var p1 = new { Id = 1, Name = "YJingLee", Age = 22 };//属性也不需要申明
var p2 = new { Id = 2, Name = "XieQing", Age = 25 };
p1 = p2;//p1,p2结构相同,可以互相赋值

var intArray = new[] { 2, 3, 5, 6 };//array
var strArray = new[] { "Hello", "World" };//array

//object array
var anonymousTypeArray = new[] 
{ 
    new { Name = "YJingLee", Age = 22 }, 
    new { Name = "XieQing", Age = 25 } 
};

var a = intArray[0];
var b = strArray[0];
var c = anonymousTypeArray[1].Name;

对象与集合初始化器(Object and Collection Initializers)

User user = new User { Id = 1, Name = "YJingLee", Age = 22 };
User user2 = new User { Id = 2, Name = "XieQing", Age = 25 };

//还可以给User类额外增加嵌套(nested)属性类型Address
User user = new User
{
    Id = 1,
    Name = "YJingLee",
    Age = 22,
    Address = new Address
    {
        City = "NanJing",
        Zip = 21000
    }
};

List<User> user = new List<User>{
    new User{Id=1,Name="YJingLee",Age=22},
    new User{Id=2,Name="XieQing",Age=25},
};

扩展方法(Extension Methods)

public static class Extensions//静态类
{
    public static bool IsValidEmailAddress(this string s)
    //静态方法和this
    {
        Regex regex = new Regex(@"^[w-.]+@([w-]+.)+[w-]{2,4}$");
        return regex.IsMatch(s);
    }
}

string 前的 this 表示是对 string 的扩展方法追加。之后 string 类型就有了一个 IsValidEmailAddress 方法。虽强大,但要慎重使用。

Comments are closed.