C# 中 Java 的默认(包)访问相当于什么?
C# 中 Java 的默认(包)访问权限相当于什么?有吗?是否有办法限制对特定名称空间的访问?
问题:
我试图将对某些方法的访问限制为仅我的 NUnit 测试 - 在 JUnit 中,我将通过进行方法包访问并将测试放在同一个包中但在 src/ 下来实现此目的test/java 而不是 src/main/java。如何在 C# 中实现类似的功能?
注意:我无法将方法设置为internal
,因为我的测试位于单独的程序集中 - 正如 NUnit 约定 - 或者是吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C# 没有包或命名空间级别的访问权限 - 只有程序集级别 - 也称为 内部访问。
但是,您可以将方法设为内部方法并使用 InternalsVisibleTo 属性将它们公开给您的单元测试程序集。
您可能会发现阅读这篇文章和这个。
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.
没有什么是完全等同的。 内部关键字很接近,但它限制了按程序集,而不是按命名空间。
如果某些内容被标记为“内部”,则只能通过同一程序集(dll、exe)中的代码访问它
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)
还有另一种截然不同的方式。 如下所示:
嵌套类可以访问其父类中的所有内容(包括私有方法)。作为构建过程(可能是 MSBuild 或 NAnt 脚本)的一部分,只需不要将测试编译为最终程序集的一部分,测试中的代码就会正常工作。
There's another way that's vastly different. You can use partial classes like so:
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.
您可以通过将方法设置为内部方法来限制这些方法仅在其程序集中可见
you could restrict the methods to be visible only in its assembly by making them internal