[Orcas] 5. Object and collection initializers

[ 2007-06-11 16:41:31 | 作者: yuhen ]
字号: | |
看完反编译的结果后,记得对编译器道声 "辛苦"。

Object initializers

注意调用构造的差别。
class MyClass
{
    public MyClass()
    {
    }

    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    private int x;

    public int X
    {
        get { return x; }
        set { x = value; }
    }

    private int y;

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    private string s;

    public string S
    {
        get { return s; }
        set { s = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass o1 = new MyClass { X = 1, Y = 2, S = "abc" };
        MyClass o2 = new MyClass { X = 1, Y = 2 };
        MyClass o3 = new MyClass(1, 2) { S = "abc" };
    }
}

反编译代码
private static void Main(string[] args)
{
    MyClass o1 = new MyClass();
    o1.X = 1;
    o1.Y = 2;
    o1.S = "abc";
    
    MyClass o2 = new MyClass();
    o2.X = 1;
    o2.Y = 2;
    
    MyClass o3 = new MyClass(1, 2);
    o3.S = "abc";
}

Collection initializers
List<int> list = new List<int> { 1, 2, 3, 4 };

List<Point> points = new List<Point> { 
    new Point { X = 1, Y = 2 }, 
    new Point { X = 1, Y = 3 } };

反编译代码
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);

List<Point> points = new List<Point>();

Point p1 = new Point();
p1.X = 1;
p1.Y = 2;
points.Add(p1);

Point p2 = new Point();
p2.X = 1;
p2.Y = 3;
points.Add(p2);

同样支持字典、哈希表等。
var arraylist = new ArrayList { "a", "b", 3 };
var hashset = new HashSet<int> { 1, 2, 3, };

var hash = new Hashtable { { "a", 1 }, { "b", 2 } };
var dict = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };

语法越来越像动态语言了。 [lol]
[最后修改由 yuhen, 于 2008-03-20 16:56:50]
评论Feed 评论Feed: http://www.rainsts.net/feed.asp?q=comment&id=503

这篇日志没有评论。

发表评论
表情图标
[smile] [confused] [cool] [cry]
[eek] [angry] [wink] [sweat]
[lol] [stun] [razz] [redface]
[rolleyes] [sad] [yes] [no]
[heart] [star] [music] [idea]
UBB代码
转换链接
表情图标
悄悄话
用户名:   密码:  
验证码 * 请输入验证码