如何使只有特定的班级可以访问班级 [英] how to make that only certain class can access a class
问题描述
我想做的是禁止SomeRandom类访问受保护的类
What I want to do is forbidding SomeRandom class accessing Protected class
public class CertainClass {
public void CerFunc(){
ProtectedClass.ProtectedFunction();
}
}
public class ProtectedClass {
public static void ProtectedFunction(){
Debug.Log("Protected");
}
}
public class SomeRandomClass {
public void RandFunc(){
ProtectedClass.ProtectedFunction(); // innaccessible due to protection level
}
}
要使其正常工作,我需要更改什么?
what do I have to change in order to make that work?
最好是静态的,因为我只需要1.
Preferably Static, because I need and want it only 1.
推荐答案
将其设为 SomeClass的私有嵌套类:
public class CertainClass
{
private class ProtectedClass
{
public static void ProtectedFunction()
{
Debug.Log("Protected");
}
}
public void CerFunc()
{
ProtectedClass.ProtectedFunction();
}
}
更新
如果您希望另一个CertainClass2
访问您的ProtectedClass
成员-
If you want another CertainClass2
to access your ProtectedClass
members -
将CertainClass2
设为CertainClass
的公共嵌套类.
OR
我建议将ProtectedClass
和其他想要访问它的类移动到另一个程序集中,并将ProtectedClass
设置为internal
,以便该程序集中的所有类都可以访问此文件类,并且对于该程序集之外的其他类是不可见的.
I would suggest to move ProtectedClass
and other classes which want to access it into another assembly and make ProtectedClass
as internal
so that all classes in that assembly can have access to this class and it is invisible to other classes outside this assembly.
这篇关于如何使只有特定的班级可以访问班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!