c# - 访问另一个类的 protected 成员

标签 c# class friend access-modifiers

我有一个 A 类,我需要从中访问 B 类的 protected 成员,就像在 C++ 中使用 friend 关键字一样。但是,内部修饰符不适合我的需要。 B 类需要创建 A 类的实例,修改其私有(private)数据,并返回对该类的引用。这些 A 类成员需要对原始调用者保密。

public class A
{
    protected int x;
}

public class B
{
    public static A CreateClassA()
    {
        A x = new A();
        x.x = 5;   // ERROR : No privilege
        return x;
    }
}

最佳答案

您可以使用 protected internal 而不是 internal 来访问同一程序集中的所有类,以及其他程序集中的子类:

public class A
{
    protected internal int x;
}

public class B
{
    public static A CreateClassA()
    {
        A x = new A();
        x.x = 5;   // hurray
        return x;
    }
}

关于c# - 访问另一个类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10375090/

相关文章:

c# - 从字符串中删除脚本和链接标签

python - 我无法使类方法起作用;如果我将方法代码复制粘贴到应该调用该方法的位置,它就可以工作

javascript - 在 es 6 中使用对象作为方法的参数

c++ - g++ 和 clang++ 与在模板类中定义的友元模板函数的不同行为

c# - 在 C# 中有什么方法可以限制 int 变量的范围?

c# - 多线程单元测试

c++ - 在类模板中没有定义参数的情况下调用 friend 模板函数

c++ - Visual Studio 与 G++ 中的 Decltype 和友元函数

c# - 简单的注入(inject)器如何针对同一接口(interface)注册/解析单例集合

javascript - .hover 不适用于我动态分配类的元素