C# dynamic type gotcha

后端 未结 2 1084
无人共我
无人共我 2020-12-05 10:40

I just ran into the strangest thing and I\'m a bit mind = blown at the moment...

The following program compiles fine but when you run it you get a <

2条回答
  •  忘掉有多难
    2020-12-05 11:35

    I guess, at runtime, container method calls are just resolved in the private Empty class, which makes your code fail. As far as I know, dynamic can not be used to access private members (or public members of private class)

    This should (of course) work :

    var num0 = ((IContainer)container).Value;
    

    Here, it is class Empty which is private : so you can not manipulate Empty instances outside of the declaring class (factory). That's why your code fails.

    If Empty were internal, you would be able to manipulate its instances accross the whole assembly, (well, not really because Factory is private) making all dynamic calls allowed, and your code work.

提交回复
热议问题