how to make that only certain class can access a class

最后都变了- 提交于 2019-12-25 04:22:14

问题


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?

Preferably Static, because I need and want it only 1.


回答1:


Make it private nested class of CertainClass:

public class CertainClass
{
    private class ProtectedClass
    {
        public static void ProtectedFunction()
        {
            Debug.Log("Protected");
        }
    }
    public void CerFunc()
    {
        ProtectedClass.ProtectedFunction();
    }
}

UPDATE

If you want another CertainClass2 to access your ProtectedClass members -

Either make CertainClass2 as public nested class of CertainClass.

OR

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.



来源:https://stackoverflow.com/questions/21651101/how-to-make-that-only-certain-class-can-access-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!