1

How does this evaluate, like, whats the flow,

This:

var tag = new TagBuilder("a");
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();

Can be turned into this:

var tag = new TagBuilder("a")
{
    MergeAttribute("href", pageUrl(i)),
    InnerHtml = i.ToString()
};

Does it go:

  1. Instastiates new object
  2. Parses the argument and sets it up
  3. Assigns all the values to the properties

Effectively does it mean the same thing, why and how?

Even if there was no "a" being parsed, would it still instantiate the object and give all the property values their defaults?

4

2 回答 2

2

这在规范的 §7.6.10.2 对象初始化器中进行了解释。从那里引用一个示例来解释如何编译对象初始值设定项:

以下类表示具有两个坐标的点:

public class Point
{
   int x, y;

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

Point可以按如下方式创建和初始化的实例:

Point a = new Point { X = 0, Y = 1 };

具有相同的效果

Point __a = new Point();
__a.X = 0;
__a.Y = 1;
Point a = __a;

where__a是一个不可见且无法访问的临时变量。

于 2013-05-25T15:39:32.313 回答
1

首先,您不能在对象初始化程序中调用方法。所以你可能有这个:

var tag = new TagBuilder("a")
{
    // MergeAttribute("href", pageUrl(i)), you can not do this
    InnerHtml = i.ToString()
};

正如@RadimKohler 所说,这是编译器提供的语法糖。您编写这样的代码,在编译时,编译器将完成其余的工作。因此,编译器生成的代码,例如:

TagBuilder tag = new TagBuilder("a");
tag.InnerHtml = i.ToString();
// the rest of your code...
于 2013-05-25T15:33:44.637 回答