如何使类在命名空间中定义的类无法访问 [英] How to make class inaccesible from outside defined in a namespace

查看:143
本文介绍了如何使类在命名空间中定义的类无法访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在命名空间中定义了两个类:例如



命名空间MyNamespace

{

公共课demo1

{

public static int Myfunction1()

{

return demo2.Myfunction2(100,400); < br $>
}

}



公共类演示2

{

public static int Myfunction2(int a,int b)

{

retutn a + b

}

}

}





我使用以下内容调用Myfunction

int result = MyNamespace.demo1.Myfunction1()调用Myfunction2



同样我可以调用MyNamespace.demo2.Myfunction2(),但我希望它无法访问办法。因为我希望用户只需调用Myfunction1,然后调用Myfunction2.user不能以任何方式调用Myfunction2。怎么做?

I have two classes defined in namespace: for example

namespace MyNamespace
{
public class demo1
{
public static int Myfunction1()
{
return demo2.Myfunction2(100,400);
}
}

public class demo2
{
public static int Myfunction2(int a, int b)
{
retutn a+b
}
}
}


I call the Myfunction using the following
int result= MyNamespace.demo1.Myfunction1() which calls Myfunction2

similarly i can call MyNamespace.demo2.Myfunction2() but i want it to be not accessible this way. Because i want user just call Myfunction1 which in turn call Myfunction2.user should not be able to call Myfunction2 by any way. How to do this?

推荐答案

不要使用静态方法。使用方法创建类,然后创建它们的实例以使用这些方法。
Don't use static methods. Create classes with methods and then create their instances to use these methods.


如果您所指的用户将通过程序集引用使用您的类,则可以阻止他访问将其标记为内部 [ ^ ]。内部类型或成员只能在同一程序集中的文件中访问。



如果用户能够将他的代码放入与您的类相同的程序集中,那么< u>将必须使该类不应使用私有或受保护的嵌套类。但是我不建议这样做,如果这只是为了隐藏课程,而不是在课堂设计的背景下实际上有意义。



修改:

If the user you're referring to will use your classes through an assembly-reference, you can prevent him from accessing a particular class by marking it as internal[^]. Internal types or members are accessible only within files in the same assembly.

If the user is able to put his code into the same assembly as your classes, then you would have to make the class that he shouldn't use a private or protected nested class. But I wouldn't recommend doing that if this would serve only the purpose of "hiding" the class and not actually making sense in the context of your class design.


// a nested class that can't be accessed "from outside":

namespace MyNamespace
{
   public class demo1
   {
      private class demo2 // or protected instead of private
      {
         public static int Myfunction2(int a, int b)
         {
            retutn a+b
         }
      }

      public static int Myfunction1()
      {
         return demo2.Myfunction2(100,400);
      }
   }
}


这篇关于如何使类在命名空间中定义的类无法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆