当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 编程技巧OOPs:复制构造函数

ASP.NET
blog程序新版本V2.0 Beta完成,提供V1.0全部源码下载
“/”应用程序中的服务器错误
asp.net(c#)复数类(复数加减乘除四则运算)
asp.net(c#)不可访问,因为它受保护级别限制
asp.net(c#) 水仙花数
ASP.NET实现用图片进度条显示投票结果
asp.net(c#) MS AJAX的安装
asp.net(c#)有关 Session 操作的几个误区
ASP.net基础知识之常见错误分析
[.net] 操纵自如-页面内的配合与通信
c# static的全部用法收集整理
使CheckBoxList的Attributes属性生效(修改微软的一个bug)
在ASP.NET中使用Session常见问题集锦
[原创]完美解决Could not load file or assembly ''AjaxPro.2'' or one of its dependencies. 拒绝访问。
在Apache环境下成功的运行ASP.NET的注意事项
ClickOnce DIY全自动更新下载升级的自我实现
asp.net jscript 一句话木马
在ASP.Net中实现flv视频转换的代码
将DataTable中的一行复制到另一个DataTable的方法
在DataTable中执行Select("条件")后,返回DataTable的方法

ASP.NET 中的 编程技巧OOPs:复制构造函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 122 ::
收藏到网摘: n/a

OOPs

1. 什么是复制构造函数

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

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

public Student(Student student)
{
this.name = student.name;
}

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

class Student
{
private string name;

public Student(string name)
{
this.name = name;
}
public Student(Student student)
{
this.name = student.name;
}

public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}

class Final

{

static void Main()

{

Student student = new Student ("A");

Student NewStudent = new Student (student);

student.Name = "B";

System.Console.WriteLine("The new student's name is {0}", NewStudent.Name);

}

}

The new student's name is A.

2.什么是只读常量

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

class Numbers
{
public readonly int m;
public static readonly int n;

public Numbers (int x)
{
m=x;
}

static Numbers ()
{
n=100;
}

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