c# - 未分配属性的对象初始值设定项

标签 c# windows-8 windows-runtime .net-4.5

我的 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/

相关文章:

c# - Dump() 对象到 JSON pretty-print 字符串

c# - 在 EF Core 中使用 UserManager 进行预加载

javascript - 从 Javascript 绑定(bind)到 MetroStyle 应用程序中的 InnerHTML

windows-8 - cygwin 上的 dotcloud 推送失败,返回 "rsync error: unexplained error (code 255)"(与 git 和 hg 类似)

windows-8 - Metro 风格 Windows 8 应用程序支持本地数据库访问吗?

c# - 无法清除 Winforms-ListBox

c# - AES 管理的加密值总是以 ==?

c# - 静态构造函数之前的异步加载设置

c# - Windows Phone 8.1 (WinRT) : Custom Looping Selector

c# - 如何在 Windows 应用商店 (WinRT) 应用程序中启用 DocumentsLibrary 功能?