Cannot assign null to anonymous property of type array

后端 未结 3 1465
野性不改
野性不改 2021-02-05 02:00

I have any array of (Pilot) objects with a (Hanger) property, which may be null, which itself has a (List) property. For test

3条回答
  •  佛祖请我去吃肉
    2021-02-05 02:41

    There are two things happening:

    Firstly, when you construct an instance of an anonymous type using new { Name = Value}, in order to build the type the compiler needs to be able to work out the type of Value. Just null on its own doesn't have a type, so the compiler wouldn't know what type to give your Planes member.

    Now, if you were using a named type for the value, you could just say (type)null and be done, BUT because you want an array of another anonymous type, there's no way to refer to is (it's anonymous!).

    So how do you get null typed as array of an anonymous type? Well, the C# spec guarantees that anonymous types with members the same names and types (in the same order!) are unified; that is, if we say

    var a = new { Foo = "Bar" };
    var b = new { Foo = "Baz" };
    

    then a and b have the same type. We can use this fact to get our suitably-typed null thus:

    var array = (new[] { new { PlaneName = "" } });
    array = null;
    

    It's not pretty but it works - now array has the right type but a null value. So this compiles:

            var array = new[] { new { PlaneName = "" } };
            array = null;
    
            var expected = new[]
                               {
                                   new
                                       {
                                           PilotName = "Higgins",
                                           Planes = array
                                       },
                                   new
                                       {
                                           PilotName = "Higgins",
                                           Planes = new[]
                                                        {
                                                            new { PlaneName = "B-52" },
                                                            new { PlaneName = "F-14" }
                                                        }
                                       }
                               };
    

提交回复
热议问题