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

ASP.NET
FreeTextBox(版本3.1.6)在ASP.Net 2.0中使用方法
.NET 常用功能和代码小结
在 .NET Framework 2.0 中未处理的异常导致基于 ASP.NET 的应用程序意外退出
asp.net IList查询数据后格式化数据再绑定控件
asp.net sql存储过程
asp.net 简单实现禁用或启用页面中的某一类型的控件
asp.net(c#)获取内容第一张图片地址的函数
The remote procedure call failed and did not execute的解决办法
ASP.NET 在线文件管理
asp.net 读取并修改config文件实现代码
ASP.NET Cookie 操作实现
asp.net Silverlight中的模式窗体
Silverlight中动态获取Web Service地址
asp.net Silverlight应用程序中获取载体aspx页面参数
asp.net 水晶报表隔行换色实现方法
asp.net 获取Gridview隐藏列的值
手动把asp.net的类生成dll文件的方法
asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页
动态指定任意类型的ObjectDataSource对象的查询参数
asp.net Md5的用法小结

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 52 ::
收藏到网摘: 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则根据实例不同而不同。