.Net Inheritance - Automatic dependency referencing behavior issue

前端 未结 3 814
长情又很酷
长情又很酷 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 02:57

    In the first scenario, you are just using the ClassA. So, it does not need the resource at compile time, just at run time.

    In the second scenario, you are inheriting from ClassA, so, its definition and information is needed by the compiler in order to build the final assembly.

    In the first scenario, VisualStudio copies the referenced DLL into the output directory, because it knows you'll need it there.

    In the second scenario, VisualStudio does not add the reference to the project, and that's I assume, your main doubt. I guess it's meant that way in order to avoid problems by being intrusive in your project. But, I'm just guessing...

    0 讨论(0)
  • 2021-01-05 03:00

    I know it's nitpicky, but I would really appreciate some consistent behavior

    It is consistant. You must reference any type that you use directly. Indirect references are resolved transparently.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题