将构造函数定义为private与其子类的构造函数有什么关系
我定义下面的类
public class Third
{
private Third()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
然后定义其子类
public class Fourthly:Third
{
private Fourthly()
{
}
}
我发现一旦把Third类的构造函数定义为private类型,那么其子类Fourthly的构造函数也会出错,提示
C:\Inetpub\wwwroot\WebApplication1\Fourthly.cs(10): 不可访问“WebApplication1.Third.Third()”,因为它受保护级别限制
这个是怎么回事,我没有用到base啊?
问题点数:20、回复次数:8Top
1 楼xinfx(新发现)回复于 2005-10-06 20:35:28 得分 0
楼上的兄弟你也太.....
Top
2 楼xinfx(新发现)回复于 2005-10-06 20:45:20 得分 0
好像在实例化子类的时候,与其父类也有关系Top
3 楼xinfx(新发现)回复于 2005-10-06 21:24:02 得分 0
比如:
public class Third
{
public string BaseTestStr;
private Third()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
BaseTestStr = "用法的测试BBBB";
}
public class Fourthly:Third
{
private Fourthly()
{
}
}
我下面实例化类Fourthly
Fourthly FClass2 = new Fourthly();
string TestValue = FClass2.BaseTestStr;
那么它照样可以访问到BaseTestStr,且其值输出为:用法的测试BBBB
Top
4 楼wuyi8808(空间/IV)回复于 2005-10-06 21:30:06 得分 18
public class Third
{
//static Third(){}
}
public class Fourthly:Third
{
private Fourthly():base(){}
}
除 System.Object 外的任何类, 如果没有显示地指明继承自什么类, 则隐式地继承自 System.Object, 如:
class SomeClass {}
相当于
class SomeClass : System.Object {}
同样,
public class Fourthly : Third
{
private Fourthly() {}
}
相当于:
public class Fourthly : Third
{
private Fourthly() : base() {}
}
Top
5 楼diandian82(点点(nothing))回复于 2005-10-06 21:30:26 得分 2
你要孩子要先有老爸!Top
6 楼wuyi8808(空间/IV)回复于 2005-10-06 21:40:31 得分 0
public class Third
{
protected Third() // <--- 如果是 private 就出错
{
System.Console.WriteLine("调用了Third的构造函数");
}
}
public class Fourthly : Third
{
private Fourthly() {} // <--- 不管有没有这一行都一样的
static void Main()
{
new Fourthly();
}
}
/* 程序输出:
调用了Third的构造函数
证明Fourthly()调用了base()
*/
Top
7 楼xinfx(新发现)回复于 2005-10-06 21:57:20 得分 0
我上面的代码有错误
public class Third
{
public string BaseTestStr;
private Third()
{
//
// TODO: 在此处添加构造函数逻辑
//
BaseTestStr = "用法的测试BBBB";
}
}
public class Fourthly:Third
{
private Fourthly()
{
}
}
Top
8 楼xinfx(新发现)回复于 2005-10-06 21:58:34 得分 0
多谢wuyi8808(空间/IV)的指点,关键是
除 System.Object 外的任何类, 如果没有显示地指明继承自什么类, 则隐式地继承自 System.Object, 如:
class SomeClass {}
相当于
class SomeClass : System.Object {}
同样,
public class Fourthly : Third
{
private Fourthly() {}
}
相当于:
public class Fourthly : Third
{
private Fourthly() : base() {}
}Top




