how to make that only certain class can access a c

2019-09-06 12:06发布

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条回答
相关推荐>>
2楼-- · 2019-09-06 12:32

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.

查看更多
登录 后发表回答