Assign to interface array initializator compiles but why?

前端 未结 4 988
星月不相逢
星月不相逢 2020-12-19 02:23

Today I was thinking it would be neat to make anonymous object which is type of some interface, and I have seen on SO that I am not only one.

Before I started checki

4条回答
  •  半阙折子戏
    2020-12-19 02:46

    it would be neat to make anonymous object which is type of some interface,

    I know there is no way to do anonymous objects implement interface, but I have not seen complaint from VS about this code.

    The problem is, you're assuming that the following code creates a new instance of an anonymous type

    new Holder { someInterface = { Property = 1 } };
    

    { Property = 1 } does not create a new instance of an anonymous type - this is an object initializer.

    If you do replace your code with a proper instantiation of an anonymous type, then the compiler will complain that the instance cannot be implicitly converted to ISomeInterface, like you expected.

    new Holder { someInterface = new { Property = 1 } };
    

提交回复
热议问题