C# - Getting references of reference

2019-07-17 18:24发布

问题:

I have built a class library project, that references a couple dll's. In the constructor of my class library project I use some enums from one of the referenced dll's. When using my class library in another project is it possible to not have to add references to my dll and the ones my class library project references internally?

回答1:

It depends on what you mean by reference internally.

If your application project uses type A from your class library, and that class does not expose any public types from other libraries, 3rd party or not, you don't need to add any references to more than your class library containing type A.

However, if type A exposes some public properties, methods returning types, or taking parameters of types, or perhaps type A is descended from a type, that is located in some other assembly, then you need a reference to that other assembly as well.

So if you indeed mean uses internally, then it should not be necessary to add more than just the one reference to your class library.

However, if the compiler complains, then that's what matters.



回答2:

You only need to reference the DLL. You only reference what you use in an assembly; the assemblies are fully self-describing individual units and thus don't require referencing the references a referenced assembly references (I am being tongue-in-cheek with my repeated use of the word 'reference' here btw :-) .

Imagine if you did have to do that - the BCL references many different things, let alone a 3rd-party component, imagine how much effort you'd have to go to just getting the references right!!



回答3:

If you are referencing any types (even if only it's their members or typed instances) that a refernced assembly is exposing then you have to include a reference to that assembly as well.



回答4:

Take your own enum in the ctor, and translate it to the 3rd party enum. I believe that'll keep your caller from having to reference the 3rd party assembly (though, of course, it'll still need to be available at runtime for your code to work).



回答5:

I think lassevk explained it concisely, but just wanted to add that although you don't need to reference those additional assemblies used by the DLL (again assuming they are only used internally and not exposed), you do still need to make them accessible to your application. That is, they must be findable--either alongside the application, or in the GAC, otherwise the DLL that uses them won't be able to find them.



回答6:

I'm not sure what are you trying to do but you don't have to reference any assembly if you don't want to . You can use reflection. It is usually regarded as a hack and is not recommendable but sometimes necessary. Here you have an article explaining how to.