What is the equivalent of Java's default (package) access in C#?

天涯浪子 提交于 2019-12-12 08:46:33

问题


What is the equivalent of Java's default (package) access in C#? Is there one? Is there anyway to restrict access to a particular namespace?

The Problem:

I'm trying to restrict access to certain methods to just my NUnit tests - in JUnit I would do this by making the methods package access and having the test in the same package but under src/test/java instead of src/main/java. How can I achieve something similar in C#?

Note: I can't make the methods internal because my tests are in a separate assembly - as is the NUnit convention - or is it?


回答1:


C# does not have package or namespace level access - only assembly level - which is also known as internal access.

However, you can make your methods internal and use the InternalsVisibleTo attribute to expose them to your unit test assembly.

You may find it useful to read this post and this one.




回答2:


There's nothing that's an exact equivalent. The internal keyword is close, but it limits by assembly, not by namespace.

If something is tagged with internal, it can only be accessed by code within the same assembly (dll, exe)




回答3:


There's another way that's vastly different. You can use partial classes like so:

  1. File #1 = code under test. Written just like normal but with the 'partial' keyword
  2. File #2 = unit test, contains a nested class that is the actual unit test.

Nested classes have access to everything in their parent class (including private methods). As part of your build process (perhaps MSBuild or NAnt scripts), just don't compile the tests as part of the final assembly, and the code-under-test will work just fine.




回答4:


you could restrict the methods to be visible only in its assembly by making them internal



来源:https://stackoverflow.com/questions/1330133/what-is-the-equivalent-of-javas-default-package-access-in-c

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