我的 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
};
}
}
最佳答案
我猜测您的第一个代码块所在的类有一个名为 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;
关于c# - 未分配属性的对象初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502963/