How to have “public public” v/s “internal public”? [duplicate]

心已入冬 提交于 2019-12-11 01:55:14

问题


Possible Duplicate:
When should [assembly: InternalsVisibleTo()] be used?
Access to dll methods

I have two assemblies, A.dll and B.dll. A.dll has some common features, and B.dll uses it. I have to distribute A.dll and B.dll for other users eventually.

However, there are some methods in A.dll that I marked as public (for use by B.dll), but I don't want anyone else to use them.

Is there a good way to achieve this? Is the use of InternalsVisibleToAttribute a good practice to achieve this?


回答1:


Mark the items as internal in A.dll and add the following assembly property

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo( "B" )]

Be warned though, you can still access internal stuff through reflection so it's not 100% sealed.




回答2:


InternalsVisibleTo is the way to go.

The title of your question was a bit confusing at first, but after reading it was clear that what you want is to have some internal (not public) members accessible by a specific assembly.




回答3:


The InternalsVisibleToAttribute attribute is one way to do this but you have to realise that it exposes all internals to the other assembly.

Also note that if you're not using signed assemblies, the InternalsVisibleToAttribute will allow access to internals from any assembly with that name. That may not be desirable.

Another option could be to use tooling to inject the required code from assembly "A" into assembly "B". That would allow "B" to function independently without accessing internals. It depends on how your assemblies are used whether that's a desirable solution or not.

Finally, you could access the code in assembly "A" using reflection. It's a bit fiddly but if there is just a couple of things you need it may be enough. This will also allow you to provide nice fallback or error handling when assembly "B" is present but A is missing.

As others have pointed out, reflection can provide access to anything in your assembly internal or not. If you need to protect your code you should look into obfuscation.



来源:https://stackoverflow.com/questions/11651086/how-to-have-public-public-v-s-internal-public

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!