using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class A
{
public void a()
{
Console.WriteLine("a");
} private void b()
{
Console.WriteLine("b");
} protected void c()
{
Console.WriteLine("c");
}
}
class Program:A
{
static void Main(string[] args)
{
A newa=new A(); //将此句话改为Program newa=new Program();
newa.a();
newa.c();
}
}
}上面为什么建立A的实例为什么不能访问protected 方法如果建立Program的实例就能访问呢? 刚学c#问题比较多 谢谢各位帮忙解答~
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class A
{
public void a()
{
Console.WriteLine("a");
} private void b()
{
Console.WriteLine("b");
} protected void c()
{
Console.WriteLine("c");
}
}
class Program:A
{
static void Main(string[] args)
{
A newa=new A(); //将此句话改为Program newa=new Program();
newa.a();
newa.c();
}
}
}上面为什么建立A的实例为什么不能访问protected 方法如果建立Program的实例就能访问呢? 刚学c#问题比较多 谢谢各位帮忙解答~
建立一个类对象,该对象只有public方法或属性才能访问
Program的实例能访问public和protected
应该详细看看protected等等词的含义和用法。
不好意思,错了,A的实例不能访问protected方法
// protected_keyword.cs
using System;
class A
{
protected int x = 123;
}class B : A
{
static void Main()
{
A a = new A();
B b = new B(); // Error CS1540, because x can only be accessed by
// classes derived from A.
// a.x = 10;
// OK, because this class derives from A.
b.x = 10;
}
}
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)
http://feiyun0112.cnblogs.com/
protected成员,在类的外部,只有子类才可以访问;
public任何代码都可以访问。
不赞同以下说法:
protected只能在类定义中访问,不能被类的实例对象访问。
建立一个类对象,该对象只有public方法或属性才能访问
protected成员可以呗该类的子类实例访问,可以被类的实例对象访问;
建立一个对象,如果该对象是继承父类的对象,那么父类的protected成员也可以被该对象访问,在类的内部,private、及protected成员也可以被该对象访问;
这样说的话 即使是在A的继承类中调用A实例的保护方法也是行不通的~