简体   繁体   中英

Accessing internal methods of nested namespace

Is is possible access function ConvertData() from function TestFunc() ?

namespace MyNameSpace
{
  internal static class Convert
  {
    internal static int ConvertData()
    {
      //code
    }
  }
}
namespace MyNameSpace.Test
{
  public class TestDataType
  {
    public void TestFunc()
    {
      int x = Convert.ConvertData()
    }
  }
}

Namespaces are irrelevant here , they are just a convenient way to arrange class and allow two classes to have the same name (as long as they are not in the same Namespace). Imagine that your hard drive doesn't allow folder and all the files are at the root level in c:\\ ! Without Namespaces, it's the same mess. (But unlike the folders of your hard drive, namespaces doesn't have access restrictions).

internal accessibility level is relative to assemblies . You can access internal members if both declaration and usage codes are in the same assembly ( example ).

If declaration and usage are in different assemblies (let's say it's declared in A and used in A.Test , a common case), yes it is feasible to access internal members declared in A from A.Test .

One achieves this by promoting the using assembly ( A.Test ) as a friend assembly of the declaring assembly ( A ).

The promotion is done in A by adding this code: [assembly: InternalsVisibleTo("A.Test")] anywhere in A code, but AssemblyInfo.cs is the preferred spot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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