开发者

access modifier that makes classes in the same folder "friends"

开发者 https://www.devze.com 2023-03-24 11:55 出处:网络
Is there a access modifier (like public, private, etc) that makes all classes in the same namespace (in the same folder) friends?

Is there a access modifier (like public, private, etc) that makes all classes in the same namespace (in the same folder) friends?

Example:

namespace MYPROJ.As {
public class A {
    _______ A() {....}
}
}

namespace MYPROJ.As {
public cl开发者_运维问答ass B {
    public DoSomething() {
        new A();   //I WANT THIS TO WORK
    }
}
}

namespace MYPROJ.Cs {
public class C {
    public DoSomething() {
        new A();   //I DON'T WANT THIS TO WORK
    }
}
}

EDIT

I want only B to be able instanciate A. How cam I do that?


If by "folder" you really mean "namespace" - no. None of the .NET access modifiers are related to namespaces at all.

Basically what controls accessibility is:

  • Being within the same class (private access)
  • Being nested within another class (private access to the containing class)
  • Being in the same assembly (internal access)
  • Being in another assembly with access via InternalsVisibleTo (internal access)
  • Being a subclass of another class (protected access to the base class members, within slightly more complicated rules)
  • Anything else (public access)

There's also protected internal, but I can never remember which way round that works, and I almost never use it :)

So if you can put class C into a different assembly to A and B (which are in the same assembly as each other), then you can make the constructor to A internal and get the result you want.


Internal is what you're looking for


Not quite, but there's internal, which limits access to classes within the same assembly (i.e. project).

0

精彩评论

暂无评论...
验证码 换一张
取 消