简体   繁体   中英

Fine-grained visibility for 'internal' members

Recently I was reading about partitioning code with .NET assemblies and stumbled upon a nice suggestion from this post : "reduce the number of your .NET assemblies to the strict minimum".

I couldn't agree more! And one of the reasons I personally see most often, is that people just want to isolate some piece of code, so they make the types/methods internal and put them into a separate project.

There are many other reasons (valid and not) for splitting code into several assemblies, but if you want to isolate components/APIs while still having them located in one library, how can you do that?

namespace MyAssembly.SomeApiInternals
{
     //Methods from this class should not 
     //be used outside MyAssembly.SomeApiInternals
     internal class Foo
     {              
          internal void Boo() { }
     }
}

namespace MyAssembly.AnotherPart
{
     public class Program
     {              
          public void Test() 
          {
               var foo = MyAssembly.SomeApiInternals.Foo();
               foo.Boo(); //Ok, not a compiler error but some red flag at least 
          }
     }
}             

How can one restrict a type/method from being used by other types/methods in the same assembly but outside this very namespace?

(I'm going to give a few answers myself and see how people would vote.)

Thanks!

您可以将代码放在不同的程序集中,然后在构建后的步骤中将程序集与ILMerge合并......

Use NDepend and put in CQL rules that embody what you want and run them as part of your build. The language isnt interested in this level of restrictions. (I hadnt followed your link yet - are you really trying to do this without NDepend? Your answer should rule it in or out)

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