2

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

应用商店版本:

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)
            };

控制台版本:

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
                          };
    }
}
4

1 回答 1

5

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

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

这也可以解释为什么您的image.Height属性是NaN-您的初始化程序从未尝试设置它。

另一方面,Program您的第二个代码块所在的类没有任何名为test3的成员,因此编译器会拒绝它。

如果您将初始化程序代码重写为老式的属性分配,问题就更清楚了:

test testObject = new test();
testObject.test1 = 5;
testObject.test2 = test3 = 6; // What is test3?
testObject.test4 = 7;
于 2013-05-12T00:47:04.023 回答