对象初始值设定项属性未分配
问题描述:
我的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)
};
控制台版本:
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
};
}
}
答
我猜在你的代码的第一个块位于曾经的属性称为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;
细看:如果你重写你的初始化代码作为老派的属性分配
的问题是清晰的。第二个对象确实有'test3'成员。 – 2013-05-12 00:48:56
他正在创建一个名为'test3'的属性的'test'类,是的,但是周围的类('Program')没有 - 他试图给属性testObject分配一个名为test3的值.test2',编译器在当前上下文中找不到该名称的变量或属性,所以它不喜欢它。 – 2013-05-12 00:50:55
+1 - 我明白你在说什么。接得好! – 2013-05-12 00:53:19