我的windows-8 app商店代码中有一个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)
};
控制台版本:
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
};
}
}
答案 0 :(得分: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;