首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类成员访问修饰符

类成员访问修饰符
EN

Stack Overflow用户
提问于 2008-10-20 20:47:35
回答 4查看 826关注 0票数 0

我希望类的方法:"One“("AccessibleWithinSameNamespace")可以由类"Two”访问,而不需要"Two“扩展"One”。

两个类都位于同一个名称空间中,所以我想也许有一个访问修饰符可以模仿“受保护的”修饰符,但是对于名称空间。

一些代码:

代码语言:javascript
复制
namespace Test
{
    class One
    {
        public void AccessibleToAll()
        {
        }


        protected void AccessibleWithinSameNamespace()
        {
            // I am not public

            // I can be accessed from other classes
            // within the same namespace of my class
        }
    }
}

namespace Test
{
    class Two
    {
        public Two()
        {
            One one = new One();

            // I am able to access this method because my class
            // is in the same namespace as the class: "One"
            one.AccessibleWithinSameNamespace();
        }
    }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2008-10-20 20:49:25

如果两个类位于同一个程序集中,则可以使用内部修饰符。

以你为例:

代码语言:javascript
复制
namespace Test
{
    class One
    {
        public void AccessibleToAll()
        {
        }


        internal void AccessibleWithinSameNamespace()
        {
            // I am not public

            // I can be accessed from other classes
            // within the same namespace of my class
        }
    }
}

namespace Test
{
    class Two
    {
        public Two()
        {
            One one = new One();

            // I am able to access this method because my class
            // is in the same namespace as the class: "One"
            one.AccessibleWithinSameNamespace();
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2008-10-20 20:57:35

C#和.NET没有“在同一个名称空间内”的概念。内部是最近的等价物。

票数 1
EN

Stack Overflow用户

发布于 2008-10-20 21:01:59

问题不是名称空间的访问修饰符,而是函数的访问修饰符。“受保护”意味着它可以由子类访问,而不是由其他类访问,即使它们位于相同的命名空间中。

你有几个解决方案可供选择..。1.您可以为函数“内部”设置访问修饰符,然后同一个程序集中的所有类/函数(或者用一些很酷的程序集标志标记,使它们假装在同一个程序集中)可以访问它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/219851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档