类的自包含???

发布时间:2024-05-14 14:20 发布:上海旅游网

问题描述:

public class mytest
{
static mytest testinstance=new mytest()

private mytest()
{
}

public mytest getinstance()
{ return testinstance}
}

怎么这里竟然是类可以自己生产自己??????

而不是被外部类生成???
一个类,可以包含自身????

如果能的话,有什么限制吗?

比如这里的包含自己的句柄是静态成员,属于类,而不属于任何实例!!!!!!

但是这个静态数据,竟然可以执行,我记得是静态乘以可以设置初值,这里竟然可以实现类???

这是c#问题,贴错目录了

问题解答:

你这段代码是单例模式的实现方法
也就是说在一个应用程序里面只有这个类的一个实例,但标准做法应该是
public class mytest
{
static mytest testinstance=new mytest();

private mytest()
{
}

public mytest getinstance()
{
if(testinstance==null)
{
testinstance=new mytest();
}
return testinstance}
}

类的成员变量,是自己的一个对象.
这种用法很多啊,比如你自己写一个链表的话,应该是这样:
class Link
{
private int data;
private Link next; //自己类的一个对象.
};

热点新闻