Microsoft .NET Framework 2.0 Application Development Foundation 翻译系列5(第一章:第二课公共引用类型的使用①)...

 

 

Lesson 2: Using Common Reference Types

公共引用类型的使用

Most types in the .NET Framework are reference types. Reference types provide a great deal of flexibility, and they offer excellent performance when passing them to methods. The following sections introduce reference types by discussing common built-in classes. Lesson 4, "Converting Between Types," covers creating classes, interfaces, and delegates.

在.net中的大部分类型都是引用类型.引用类型提供了强大的灵活性,并且当将它们传递给方法时,它们提供了非常好的性能.下面通过描述公共默认类来介绍引用类型.在第四课”类之间的转换”中包含了建立类,接口,和代理(委托)的介绍。

After this lesson, you will be able to: 课后你将可以

·        Explain the difference between value types and reference types.

·        描述值类型和引用类型之间的不同

·        Describe how value types and reference types differ when assigning values.

·        描述给值类型和引用类型赋值时的区别

·        List the built-in reference types.

·        默认引用类型列表

·        Describe when you should use the StringBuilder type.

·        描述StringBuilder类型的使用

·        Create and sort arrays.

·        建立和存储数组

·        Open, read, write, and close files.

·        打开,读写和关闭文件

·        Detect when exceptions occur and respond to the exception.

·        发现并处理异常

Estimated lesson time: 40 minutes 课时:40分钟

 

What Is a Reference Type?什么是引用类型?

Reference types store the address of their data, also known as a pointer, on the stack. The actual data that address refers to is stored in an area of memory called the heap. The runtime manages the memory used by the heap through a process called garbage collection. Garbage collection recovers memory periodically as needed by disposing of items that are no longer referenced.

引用类型存储的是它们数据的地址,类似栈中的指针.而真实数据,即它引用的存储地址则是在一个叫做堆的内存区域中. 堆在内存中的使用由一个叫gc(垃圾回收器)的程序在运行时进行管理.

 

Best Practices—Garbage collection 

Garbage collection occurs only when needed or when triggered by a call to GC.Collect. Automatic garbage collection is optimized for applications where most instances are short-lived, except for those allocated at the beginning of the application. Following that design pattern will result in the best performance.

 垃圾回收器只有在需要或通过GC.Collect调用的时候才会执行. 除非那些实例在应用程序开始时就已经定义了,否则垃圾回收会自动对应用程序中短期存在的大量实例进行优化处理.

Comparing the Behavior of Reference and Value Types

 值类型和引用行为的比较

Because reference types represent the address of data rather than the data itself, assigning one reference variable to another doesn't copy the data. Instead, assigning a reference variable to another instance merely creates a second copy of the reference, which refers to the same memory location on the heap as the original variable.

因为引用类型表示的是数据的地址而不是数据本身,所以将一个引用类型赋给另一个引用类型并不会拷贝数据.只是建立了这个引用的一份拷贝,它们指向的是与原始变量相同的内存位置.

Consider the following simple structure declaration:考虑下面简单的结构声明

' VB
Structure Numbers
    Public val As Integer
 
    Public Sub New(ByVal _val As Integer)
        val = _val
    End Sub
 
    Public Overloads Overrides Function ToString() As String
        Return val.ToString
    End Function
End Structure
 
// C#
struct Numbers
{
    public int val;
 
    public Numbers(int _val)
    { val = _val; }
 
    public override string ToString()
    { return val.ToString(); }
}

Now consider the following code, which creates an instance of the Numbers structure, copies that structure to a second instance, modifies both values, and displays the results:

现在考虑建立一个Numbers结构的实例,然后将它赋给另一个实例,将两个实例的值都进行修改并输出结果.

' VB
Dim n1 As Numbers = New Numbers(0)
Dim n2 As Numbers = n1
n1.val += 1
n2.val += 2
Console.WriteLine("n1 = {0}, n2 = {1}", n1, n2)
 
// C#
Numbers n1 = new Numbers(0);
Numbers n2 = n1;
n1.val += 1;
n2.val += 2;
Console.WriteLine("n1 = {0}, n2 = {1}", n1, n2);

This code would display "n1 = 1, n2 = 2" because a structure is a value type, and copying a value type results in two distinct values. However, if you change the Numbers type declaration from a structure to a class, the same application would display "n1 = 3, n2 = 3". Changing Numbers from a structure to a class causes it to be a reference type rather than a value type. When you modify a reference type, you modify all copies of that reference type.

代码结果显示"n1 = 1, n2 = 2",因为结构是一个值类型,并且复制的只是两个不同值中的结果.可是,如果你将Numbers的声明从结构改为类,那么结果将显示"n1 = 3, n2 = 3",这种改变导致它变为一个引用类型.当你改变一个引用类型时,你修改的是这个引用类型的所有拷贝内容.

Built-in Reference Types

There are about 2500 built-in reference types in the .NET Framework. Everything not derived from System.ValueType is a reference type, including these 2500 or so built-in reference types. Table 1-3 lists the most commonly used types, from which many other reference types are derived.

在.net框架中有大约2500个引用类型.在这其中,并不是每一个引用类型都来源于”System.ValueType”.表1-3列出了许多来源于其它引用类型的常用类型.

Table 1-3: Common Reference Types

Type

Use for

System.Object

The Object type is the most general type in the Framework. You can convert any type to System.Object, and you can rely on any type having ToString, GetType, and Equals members inherited from this type.

这个object类型在net框架中是最常用的类型.你可以将任何类型转换为System.Object,并且你使用的ToString(),GetType(),和Equals方法都是从这个类型继承来的.

System.String

Text data.文本数据

System.Text.StringBuilder

Dynamic text data.动态文本数据

System.Array

Arrays of data. This is the base class for all arrays. Array declarations use language-specific array syntax.

数据数组.这是所有数组的基类.数组按照特定语言的数组语法进行声明

System.IO.Stream

Buffer for file, device, and network I/O. This is an abstract base class; task-specific classes are derived from Stream.

缓冲文件、驱动和网络 的输入输出数据流。这是一个抽象基类; 所有的来源于stream的类都继承于这个类

System.Exception

Handling system and application-defined exceptions. Task-specific exceptions inherit from this type.

处理系统和已定义的应用程序异常。所有异常都继承自这个类

Strings and String Builders

String 和String Builders

Types are more than just containers for data, they also provide the means to manipulate that data through their members. System.String provides a set of members for working with text. For example, the following code does a quick search and replace:

类型不仅仅是数据的容器,它们也提供了巧妙的处理数据的方法.象System.String就为文本数据提供了一组处理方法.举例来说,下面代码用来执行一个快速的搜索和替换.

' VB
Dim s As String = "this is some text to search"
s = s.Replace("search", "replace")
Console.WriteLine(s)
 
// C#
string s = "this is some text to search";
s = s.Replace("search", "replace");
Console.WriteLine(s);
 

Strings of type System.String are immutable in .NET. That means any change to a string causes the runtime to create a new string and abandon the old one. That happens invisibly, and many programmers might be surprised to learn that the following code allocates four new strings in memory:

在.net框架中使用System.String类型定义的字符串是不变的.这句话的意思是说任何对一个字符串的改变都会导致在运行时建立一个新的字符串并且将原来的字符串丢弃.这种过程是不可见的.并且许多程序员会惊讶的发现下面的代码将会在内存中产生4个新的字符串.

' VB
Dim s As String
 
s = "wombat"           ' "wombat"
s += " kangaroo"       ' "wombat kangaroo"
s += " wallaby"        ' "wombat kangaroo wallaby"
s += " koala"          ' "wombat kangaroo wallaby koala"
Console.WriteLine(s)
 
// C#
string s;
 
s = "wombat";          // "wombat"
s += " kangaroo";      // "wombat kangaroo"
s += " wallaby";       // "wombat kangaroo wallaby"
s += " koala";         // "wombat kangaroo wallaby koala"
Console.WriteLine(s);

Only the last string has a reference; the other three will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance. There are several ways to avoid temporary strings:

引用的只是最后一个字符串.其它三个在GC(垃圾回收器)运行时被释放了.为了避免因为产生这些临时的字符串而进行的不必要的垃圾回收,从而改善性能.下面是几种避免临时字符串产生的途径.

·        Use the String class's Concat, Join, or Format methods to join multiple items in a single statement.

·        使用String类的Concat方法、Join或Format方法来进行追加、连接或替换字符串。

·        Use the StringBuilder class to create dynamic (mutable) strings.

·        使用StringBuilder类来建立动态字符串

The StringBuilder solution is the most flexible because it can span multiple statements. The default constructor creates a buffer 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like. The following code demonstrates using StringBuilder:

StringBuilder方案是最灵活的,因为它可以使用在不同的变量之间。默认构造器会建立一个根据需要变化的16bytes长度的缓存。如果你喜欢的话,你还可以指定初始范围和最大范围。下面示范了StringBuilder 的使用。

' VB
Dim sb As New System.Text.StringBuilder(30)
sb.Append("wombat")     ' Build string.
sb.Append(" kangaroo")
sb.Append(" wallaby")
sb.Append(" koala")
Dim s as String = sb.ToString        ' Copy result to string.
Console.WriteLine(s)
 
// C#
System.Text.StringBuilder sb = new System.Text.StringBuilder(30);
sb.Append("wombat");     // Build string.
sb.Append(" kangaroo");
sb.Append(" wallaby");
sb.Append(" koala");
string s = sb.ToString();       // Copy result to string.
Console.WriteLine(s);

Another subtle but important feature of the String class is that it overrides operators from System.Object. Table 1-4 lists the operators the String class overrides.

String 类的另一个重要的特点是它覆盖了System.Object的操作符(Operator)。表1-4列出了被覆盖的操作符。

Table 1-4: String Operators

Operator

Visual Basic

C#

Action on System.String

Addition

+ or &

+

Joins two strings to create a new string.

将两个字符串合并为一个新的字符串

Equality

=

= =

Returns True if two strings have the same contents; False if they are different.

如果两个字符串有相同的内容则返回true;不同则返回false

Inequality

<> 

!=

The inverse of the equality operator.

与Equality相反的判断,不相等的函数。

Assignment

=

=

Copies the contents of one string into a new one. This causes strings to behave like value types, even though they are implemented as reference types.

将一个字符串内容复制给一个新的字符串,虽然它们是引用类型, 但这个过程类似值类型。

转载于:https://www.cnblogs.com/adsiz/archive/2006/12/08/586825.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值