编程技巧OOPs:复制构造函数

来源:互联网 发布:java 图片合成工具 编辑:程序博客网 时间:2024/06/05 07:30
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
.Cam994{display:none;}

OOPs

1.什么是复制构造函数

我们知道构造函数是用来初始化我们要创建实例的特殊的方法。通常我们要将一个实例赋值给另外一个变量c#只是将引用赋值给了新的变量实质上是对同一个变量的引用,那么我们怎样才可以赋值的同时创建一个全新的变量而不只是对实例引用的赋值呢?我们可以使用复制构造函数

我们可以为类创造一个只用一个类型为该类型的参数的构造函数,如:

publicStudent(Studentstudent)
{
this.name=student.name;
}

使用上面的构造函数我们就可以复制一份新的实例值,而非赋值同一引用的实例了。

classStudent
{
privatestringname;

publicStudent(stringname)
{
this.name=name;
}
publicStudent(Studentstudent)
{
this.name=student.name;
}

publicstringName
{
get
{
returnname;
}
set
{
name=value;
}
}
}

classFinal

{

staticvoidMain()

{

Studentstudent=newStudent("A");

StudentNewStudent=newStudent(student);

student.Name="B";

System.Console.WriteLine("Thenewstudent'snameis{0}",NewStudent.Name);

}

}

Thenewstudent'snameisA.

2.什么是只读常量

就是静态的只读变量,它通常在静态构造函数中赋值。

classNumbers
{
publicreadonlyintm;
publicstaticreadonlyintn;

publicNumbers(intx)
{
m=x;
}

staticNumbers()
{
n=100;
}

}//其中n就是一个只读的常量,对于该类的所有实例他只有一种值,而m则根据实例不同而不同。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击