如何使只有特定的班级可以访问班级 [英] how to make that only certain class can access a class

查看:102
本文介绍了如何使只有特定的班级可以访问班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是禁止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屋!

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