未初始化属性的对象初始值设定项

N_A*_*N_A 2 c# windows-8 windows-runtime .net-4.5

我的windows-8应用程序商店代码中有一个type-o.我得到了一个奇怪的结果,所以我回去看看并意识到我错过了一个值,但它仍然编译并运行没有错误.认为这很奇怪,我在Windows 8控制台应用程序中尝试了它,在这种情况下,这是一个编译错误!是什么赋予了?

App store版本:

var image = new TextBlock()
            {
                Text = "A",    //Text is "A"
                FontSize =     //FontSize is set to 100
                Height = 100,  //Height is NaN
                Width = 100,   //Width is 100
                Foreground= new SolidColorBrush(Colors.Blue)
            };
Run Code Online (Sandbox Code Playgroud)

控制台版本:

public class test
{
    public int test1 { get; set; }
    public int test2 { get; set; }
    public int test3 { get; set; }
    public int test4 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        test testObject = new test()
                          {
                              test1 = 5,
                              test2 =
                              test3 = 6, //<-The name 'test3' does not exist in the current context                         
                              test4 = 7
                          };
    }
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*odd 5

我猜你的第一个代码块所在的类有一个名为的属性Height,因此编译器将其解释为:

var image = new TextBlock()
            {
              Text = "A",
              FontSize = this.Height = 100,
              Width = 100,
              Foreground = new SolidColorBrush(Colors.Blue)
            };
Run Code Online (Sandbox Code Playgroud)

这也可以解释为什么你的image.Height财产是NaN- 你的初始化者从未试图设置它.

另一方面,Program第二个代码块所在的类没有任何命名成员test3,因此编译器对其进行了禁止.

如果您将初始化代码重写为旧学校属性分配,问题会更清楚:

test testObject = new test();
testObject.test1 = 5;
testObject.test2 = test3 = 6; // What is test3?
testObject.test4 = 7;
Run Code Online (Sandbox Code Playgroud)