StackOverflowException when accessing member of nested class via a dynamic reference

后端 未结 2 1687
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 07:39

I have defined a generic class that derives from BindingList and has a nested non-generic class:

class Generic : BindingList.Inn         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 08:30

    I think the problem is in this place

    Generic :BindingList.Inner>
    

    Notice you use the declared class as a generic parameter in the parent class BindingList. So I believe reflection just ends up with an infinitive loop and you get StackOverflow.

    When you use

    var d = new Generic.Inner();
    

    compiler just replaces it with Generic.Inner so it is the same like

    Generic.Inner d = new Generic.Inner();
    

    But when you use

    dynamic d = new Generic.Inner();
    

    You really use reflection. Again reflection starts digging deeper in your class structure and it goes like... your class => BindingList = > generic parameter of BindingList => your class(because it's a generic parameter of BindingList) = > BindingList = > and so on until you get StackOverflow.

    You can change to Generic : BindingList to break this infinitive loop and it works!

提交回复
热议问题