.Net Inheritance - Automatic dependency referencing behavior issue

前端 未结 3 847
长情又很酷
长情又很酷 2021-01-05 02:42

I\'ve come across a strange issue that I\'ve just now noticed.

If you have a solution with 3 projects

** NOTE Edited after discussion **

Project LibA

3条回答
  •  忘掉有多难
    2021-01-05 03:03

    This is consistent behaviour. The first one is a simple reference, the second one is inheritance.

    If an assembly is compiled and a class inherits from a class in another assembly, that reference is required to construct it.

    LibB only contains the information that is added in the class definition of ClassB, it doesn't copy everything from LibA (this would produce inconsistent code if LibA is updated and ClassA is changed while doing that, LibB would still contain the old information).

    So to use an inherited class definition in LibC, it needs both the information from LibA (for ClassA) and LibB (ClassB) to construct it, thus a direct reference to LibA is needed.

    In the example, all references to classes of different assemblies are private, thus only the next level is neeed (ClassC doesn't need to know about ClassA as there is no direct usage of that class). If the usage of ClassA in ClassB was a public field or propety, ClassC would have a direct reference to ClassA and would need a direct reference to that class definition as well (reference to LibA from LibC).

    In a different form, this is also the case in the inheritance example. ClassC has a direct reference to ClassA (due to ClassB inherting from ClassA), thus a reference to the declaring assembly (namely LibA) is needed to construct the full class definition.

提交回复
热议问题