Cannot assign null to anonymous property of type array

后端 未结 3 1464
野性不改
野性不改 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:56

    You have to use a typed null:

    (List)null
    

    Or

    (Plane[])null
    

    Otherwise the compiler has no idea what type you want the anonymous type's member to be.

    Update As @AakashM has rightly pointed out - this solves your problem of assigning a null to an anonymous member - but doesn't actually compile - and if it did it wouldn't allow you to refer to these members.

    A fix would be to do this (unfortunately both the null and the anonymous Planes array will need casting:

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

    So use IEnumerable as the member type. You could also use IEnumerable but the effect will be the same either way.

    Or - you could use IEnumerable as the common type - this would let you do this:

    Assert.AreEqual("B-52", expected[1].Planes.First().PlaneName);
    

    提交回复
    热议问题