简体   繁体   中英

Object Initializer where property isn't assigned

I had a type-o in my windows-8 app store code. I got a strange result, so I went back to look and realized I missed a value, but it still compiled and ran without errors. Thinking this was strange, I went and tried it in a windows 8 console application, and in that context it is a compile error! What gives?

App store version:

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

Console version:

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

I'm guessing the class in which your first block of code was located had a property called Height , and so the compiler was interpreting it as:

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

That would also explain why your image.Height property was NaN -- your initializer never tried to set it.

On the other hand, the Program class where your second block of code is located doesn't have any members named test3 , and so the compiler barfed on it.

The problem is clearer if you rewrite your initializer code as old-school property assignments:

test testObject = new test();
testObject.test1 = 5;
testObject.test2 = test3 = 6; // What is test3?
testObject.test4 = 7;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM