简体   繁体   English

在C#中,Java的默认(包)访问权限相当于什么?

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

What is the equivalent of Java's default (package) access in C#? 在C#中,Java的默认(包)访问权限相当于什么? 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. 我试图限制对某些方法的访问仅限于我的NUnit测试 - 在JUnit中我会通过使方法包访问并在同一个包中但在src / test / java而不是src / main / java下进行测试来实现这一点。 How can I achieve something similar in C#? 如何在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? 注意:我不能将方法设置为internal因为我的测试是在一个单独的程序集中 - 就像NUnit约定一样 - 或者是它?

C# does not have package or namespace level access - only assembly level - which is also known as internal access. C#没有包级别或命名空间级别访问权限 - 只有程序集级别 - 也称为内部访问权限。

However, you can make your methods internal and use the InternalsVisibleTo attribute to expose them to your unit test assembly. 但是,您可以将方法设置为内部,并使用InternalsVisibleTo属性将它们公开给单元测试程序集。

You may find it useful to read this post and this one . 你可能会发现阅读这篇文章和这篇文章很有用。

There's nothing that's an exact equivalent. 没有什么是完全相同的。 The internal keyword is close, but it limits by assembly, not by namespace. internal关键字是close,但它受程序集限制,而不是命名空间。

If something is tagged with internal, it can only be accessed by code within the same assembly (dll, exe) 如果某些内容被标记为内部,则只能通过同一程序集中的代码访问它(dll,exe)

There's another way that's vastly different. 另一种方式却截然不同。 You can use partial classes like so: 你可以像这样使用部分类

  1. File #1 = code under test. 文件#1 =正在测试的代码。 Written just like normal but with the 'partial' keyword 写的就像正常但有'部分'关键字
  2. File #2 = unit test, contains a nested class that is the actual unit test. 文件#2 =单元测试,包含一个嵌套类,它是实际的单元测试。

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. 作为构建过程的一部分(可能是MSBuild或NAnt脚本),只是不要将测试编译为最终程序集的一部分,并且测试中的代码可以正常工作。

您可以通过将方法设置为内部来限制方法仅在其程序集中可见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM