首页 > Web开发 > 详细

[.net基础]访问修饰符

时间:2014-03-13 06:18:18      阅读:448      评论:0      收藏:0      [点我收藏+]

标题:[.net基础]访问修饰符

一、前言

基础掌握不牢固啊,所以记录下来。

二、正文

1、方法访问修饰符Internal

  (1)、创建工程ParentAndSon

  (2)、添加类ModelA

bubuko.com,布布扣
bubuko.com,布布扣
namespace ParentAndSon
{
    public class ModelA
    {
        internal void TestInternal()
        {
        }

        protected void TestProtected()
        {
        }

        protected internal void TestProtectedInternal()
        {
        }
    }
}
View Code
bubuko.com,布布扣

  (3)、添加测试类MainIn,注意命名空间和ModelA相同

bubuko.com,布布扣
bubuko.com,布布扣
namespace ParentAndSon
{
    public class MainIn
    {
        public static void Main(string[] arg)
        {
            ModelA a = new ModelA();
            a.TestInternal();
            //a.TestProtected();
            a.TestProtectedInternal();
        }
    }
}
View Code
bubuko.com,布布扣

  可看出,只有protected修饰的无法访问,internal和protected internal修饰的方法均可访问。

  (4)、添加测试类InvokeModelA,注意命名空间和ModelA不同

bubuko.com,布布扣
bubuko.com,布布扣
namespace SomeNameSpace
{
    public class InvokeModelA
    {
        public InvokeModelA()
        {
            ModelA a = new ModelA();
            a.TestInternal();
            //a.TestProtected();
            a.TestProtectedInternal();
        }
    }
}
View Code
bubuko.com,布布扣

  可看出,只有protected修饰的无法访问,internal和protected internal修饰的方法均可访问。

  (5)、创建新工程TestParentAndSon,以下操作均在TestParentAndSon项目中。

  (6)、添加测试类Program,注意命名空间和ModelA不同

bubuko.com,布布扣
bubuko.com,布布扣
namespace TestParentAndSon
{
    class Program
    {
        static void Main(string[] args)
        {
            ModelA a = new ModelA();
            //a.TestInternal();
            //a.TestProtected();
            //a.TestProtectedInternal();
        }
    }
}
View Code
bubuko.com,布布扣

  可看出,protected、internal和protected internal修饰的方法均不可访问。

  (7)、添加测试类TestA,注意命名空间和ModelA相同

bubuko.com,布布扣
bubuko.com,布布扣
namespace ParentAndSon
{
    public class TestA
    {
        public TestA()
        {
            ModelA a = new ModelA();
            //a.TestInternal();
            //a.TestProtected();
            //a.TestProtectedInternal();
        }
    }
}
View Code
bubuko.com,布布扣

  可看出,protected、internal和protected internal修饰的方法均不可访问。
  (8)、添加子类Son

bubuko.com,布布扣
bubuko.com,布布扣
namespace TestParentAndSon
{
    public class Son : ModelA
    {
        public Son()
        {
            //this.TestInternal();
            this.TestProtected();
            this.TestProtectedInternal();
        }
    }
}
View Code
bubuko.com,布布扣

  可看出,internal修饰的方法不可访问,而protected和protected internal修饰的方法可以访问。

总结:

  internal修饰符是针对同一程序集的,如果是同一程序集,则可以访问,否则不可访问。

  protected是针对子类的,不管是否位于同一个程序集。

  protected internal是把两者的优点集合到一起了,范围比两者任何一个都大。

[.net基础]访问修饰符,布布扣,bubuko.com

[.net基础]访问修饰符

原文:http://www.cnblogs.com/fiteg/p/3596701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!