Microsoft .NET Framework 2.0 Application Development Foundation 翻译系列8(第一章:第四课 类型转换)...

 

Lesson 4: Converting Between Types类型转换

Often, you need to convert between two different types. For example, you might need to determine whether an Integer is greater or less than a Double. You might need to pass a Double to a method that requires an Integer as a parameter. Or you might need to display a number as text.

你经常需要在两个不同类型之间进行转换。例如,你也许需要确定一个Integer是大于还是小于一个Double。你可能要传递一个Double给一个方法,但却将Integer作为参数。或者你可能需要以文本的方式显示数字。

This lesson describes how to convert between types in both Visual Basic and C#. Type conversion is one of the few areas where Visual Basic and C# differ considerably.

本课讨论,在VB和C#中,如何在类型之间进行转换。类型转换只是VB和C#那少的可怜的区别之一。

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

·         Convert between types.进行类型间的转换

·         Explain boxing and why it should be avoided.解释装箱和为什么要避免它。

·         Implement conversion operators.实现转换操作符

Estimated lesson time: 20 minutes 本课时20分钟

 

Conversion in Visual Basic and C# VB和C#中的转换

By default, Visual Basic allows implicit conversions between types, while C# prohibits implicit conversions that lose precision. To turn off implicit conversions in Visual Basic, add Option Strict On to the top of each code file, or (in Visual Studio) select Project, choose Properties, select Compile, and select Option Strict On for the entire project.

Both Visual Basic and C# allow implicit conversion if the destination type can accommodate all possible values from the source type. That is called a widening conversion, and it is illustrated by the following example:

默认情况下,VB允许类型之间进行隐式转换(implicit conversions),这与C#不允许隐式转换相比丧失了精度。可以通过在每个Vb代码文件顶部添加“Option Strict On”(参考下面注解)来关闭隐式转换。或者(在VS中)选择项目(project)-》属性(properties)-》编译(complie)-》Option Strict On来为全部的项目取消隐式转换。在目的类型可以提供源类型包含的所有可能的值的情况下,Vb和C#都允许隐式转换。这叫做一个“放大转换”。 (这句话的意思是,源类型的值的范围小于等于目的类型的值的范围。或者说将小范围的类型转换为大范围的类型。例如:int16 to int32)通过下面实例来说明:

注解:Option Explicit:用于在文件级强制对该文件中的所有变量进行显式声明。 =on,用变量之前必须先申明,否则编缉出错!反之不必申就可以用。Option Strict是用来约束数据类型是否隐式转换还是不转换。

' VB
Dim i As Integer = 1
Dim d As Double = 1.0001
d = i       ' Conversion allowed
 
// C#
int i = 1;
double d = 1.0001;
d = i;   // Conversion allowed.

If the range or precision of the source type exceeds that of the destination type, the operation is called a narrowing conversion, which usually requires explicit conversion. Table 1-7 lists the ways to perform explicit conversions.

假设源类型的范围和精度都超过了目的类型,这个操作被成为:“缩小转换”, (这句话的意思是,大范围的类型转换为小范围的类型。例如:int32 to int16)通常这种情况要求“显示转换”(explicit conversion)。表1-7列出了执行显示转换的方法。

Table 1-7: Methods for Explicit Conversion 显式转换的方法

System Type

Visual Basic

C#

Converts

System.Convert

 

 

Between types that implement the System.IConvertible interface.

在实现了System.IConvertible接口的类型之间转换。

 

CType

(type) cast operator

Between types that define conversion operators.

在定义了转换操作符的类型之间转换

type.ToString, type.Parse

 

 

Between string and base types; throws exception if the conversion is not possible.

在string和基本类型间转换,如果不能转换抛出异常。

type.TryParse, type.TryParseExact

 

 

From string to a base type; returns false if the conversion is not possible.

将string转换为一个基本类型,如果不能转换则返回fasle

 

CBool, CInt, CStr, etc.

 

Between base Visual Basic types; compiled inline for better performance. (Visual Basic only.)

在VB基本类型间转换;内嵌编译器提供更好的性能(只在VB使用)

 

DirectCast, TryCast

 

Between types. DirectCast throws an exception if the types are not related through inheritance or if they do not share a common interface; TryCast returns Nothing in those situations. (Visual Basic only.)

类型之间转换。如果类型没有继承关系或它们不继承于同一个接口,那么DirectCast将抛出一个异常;TryCast在这些情况下返回Nothing。(只能在VB中使用)

 

 

.NET 2.0 

TryParse, TryParseExact, and TryCast are new in .NET 2.0. Previously, you had to attempt a parsing or conversion and then catch the exception if it failed.

TryParse,TryParseExact,和TryCast是在net2.0中新提供的。以前,你必须尝试一次解析(parsing)或转换,如果失败,那么捕获这个异常。

Narrowing conversions fail if the source value exceeds the destination type's range or if a conversion between the types is not defined, so you should enclose a narrowing conversion in Try blocks or use TryCast or TryParse and check the return value.

如果源类型的值超出了目的类型的范围或者转换中的类型没有被定义,会产生缩小转换(Narrowing conversions)失败。因此,你要将缩小转换放在Try块中,或用TryCast,再或者用TryParse并检查返回值。

What Is Boxing and Unboxing?什么是装箱和拆箱?

Boxing converts a value type to a reference type, and unboxing converts a reference type to a value type. The following example demonstrates boxing by converting an Integer (a value type) to an Object (a reference type):

装箱是将一个值类型转换为一个引用类型,而拆箱是将一个引用类型转换为一个值类型。下面例子通过转换一个Integer(值类型)到一个Object(引用类型)来演示装箱:

'VB
Dim i As Integer = 123
Dim o As Object = CType(i, Object)
 
// C#
int i = 123;
object o = (object) i;

Unboxing occurs if you assign a reference object to a value type. The following example demonstrates unboxing:

如果你将一个引用类型赋给一个值类型将会导致拆箱。下面代码示范拆箱:

'VB
Dim o As Object = 123
Dim i As Integer = CType(o, Integer)
 
// C#
object o = 123;
int i = (int) o;
 

 

Best Practices—Boxing and unboxing 

Boxing and unboxing incur overhead, so you should avoid them when programming intensely repetitive tasks. Boxing also occurs when you call virtual methods that a structure inherits from System.Object, such as ToString. Follow these tips to avoid unnecessary boxing:

装箱和拆箱将产生损耗,因此当程序总是重复这类任务时,你应该避免它们。当你调用派生于System.Object类的结构的虚函数时也将会导致装箱。例如,ToString。

下面这些提示用于避免不必要的装箱:

·         Implement type-specific versions (overloads) for procedures that accept various value types. It is better practice to create several overloaded procedures than one that accepts an Object argument.

·         为程序实现明确说明的类型(重载),使它可以接收各式各样的值类型。而接收Object类型参数对于建立重载过程是一个好的习惯。

·         Use generics whenever possible instead of accepting Object arguments.

·         尽可能的使用泛型代替Object类型。

·         Override the ToString, Equals, and GetHash virtual members when defining structures.

·         当定义结构时,覆盖ToString,Equals,和GetHash这些虚方法。

How to Implement Conversion in Custom Types如何实现自定义类型的转换

You can define conversions for your own types in several ways. Which technique you choose depends on the type of conversion you want to perform:

你可以通过几种方法来对自定义类型进行转换。那么,你想要完成这种类型转换需要哪几项技术呢?

·         Define conversion operators to simplify narrowing and widening conversions between numeric types.

·         定义转换操作符来简化数字类型之间的缩小和放大转换。

·         Override ToString to provide conversion to strings, and override Parse to provide conversion from strings.

·         覆盖ToString来提供转换到字符串功能,并且,覆盖Parse来提供将字符串转换为本类型的功能。

·         Implement System.IConvertible to enable conversion through System.Convert. Use this technique to enable culture-specific conversions.

·         实现System.IConvertible接口来允许通过System.Convert转换。使用这个技巧来实现特定类型的转换。

·         Implement a TypeConverter class to enable design-time conversion for use in the Visual Studio Properties window. Design-time conversion is outside the scope of the exam and the TypeConverter class is not covered in this book.

·         实现一个TypeConverter类,这样允许在VS属性窗体中设计时进行转换。设计时转换是考试范围外的内容,但TypeConverter类在这本书中仍会被介绍。

 

More Info—Design-time conversion 

For more information about design-time conversion, read "Extending Design-Time Support" at http://msdn2.microsoft.com/en-us/library/37899azc(en-US,VS.80).aspx.

关于设计时转换的更多信息可以访问http://msdn2.microsoft.com/en-us/library/37899azc(en-US,VS.80).aspx.页面中的“扩展设计时支持”

 

 

.NET 2.0 

Conversion operators are new in .NET 2.0.

转换操作符是net2.0中新提供的功能。

Defining conversion operators allows you to directly assign from a value type to your custom type. Use the Widening/implicit keyword for conversions that don't lose precision; use the Narrowing/explicit keyword for conversions that could lose precision. For example, the following structure defines operators that allow assignment to and from integer values:

定义转换操作符可以允许你直接将一个值类型赋给你的自定义类型。转换时使用Widening/implicit关键字可以保证转换的精度;转换时使用Narrowing/Explicit关键字无法保证精度。例如,下面的结构定义了操作符,它允许分配并获取整型数值。

' VB
Structure TypeA
    Public Value As Integer
 
    ' Allows implicit conversion from an integer.
    Public Shared Widening Operator CType(ByVal arg As Integer) As TypeA
        Dim res As New TypeA
        res.Value = arg
        Return res
    End Operator
 
    ' Allows explicit conversion to an integer
    Public Shared Narrowing Operator CType(ByVal arg As TypeA) As Integer
        Return arg.Value
    End Operator
 
    ' Provides string conversion (avoids boxing).
    Public Overrides Function ToString() As String
        Return Me.Value.ToString
    End Function
 
End Structure
 
// C#
struct TypeA
 
{
    public int Value;
 
// Allows implicit conversion from an integer.允许将一个integer隐式转换为TypeA
 
    public static implicit operator TypeA(int arg)
    {
        TypeA res = new TypeA();
        res.Value = arg;
        return res;
    }
 
    // Allows explicit conversion to an integer.允许将TypeA显式转换为int
    public static explicit operator int(TypeA arg)
    {
        return arg.Value;
    }
 
    // Provides string conversion (avoids boxing).提供字符串转换
    public override string ToString()
    {
        return this.Value.ToString();
    }
}

The preceding type also overrides ToString to perform the string conversion without boxing. Now you can assign integers to the type directly, as shown here:

上述类型也覆盖了ToString方法,但字符串转换的执行并不会产生装箱。现在,你可以将integer直接赋给这个类型,象下面显示的:

' VB
Dim a As TypeA, i As Integer
' Widening conversion is OK implicit.
a = 42 ' Rather than a.Value = 42
' Narrowing conversion must be explicit.
i = CInt(a) ' Rather than i = a.Value
' This syntax is OK, too.
i = CType(a, Integer)
Console.WriteLine("a = {0}, i = {0}", a.ToString, i.ToString)
 
// C#
TypeA a; int i;
// Widening conversion is OK implicit.放大转换可以是隐式的
a = 42; // Rather than a.Value = 42
// Narrowing conversion must be explicit.缩小转换必须是显式的。
i = (int)a; // Rather than i = a.Value
Console.WriteLine("a = {0}, i = {0}", a.ToString(), i.ToString());

To implement the System.IConvertible interface, add the IConvertible interface to the type definition. Then use Visual Studio to automatically implement the interface. Visual Studio inserts member declarations for 17 methods, including GetTypeCode, ChangeType, and ToType methods for each base type. You don't have to implement every method, and some-such as ToDateTime-will probably be invalid. For invalid methods, simply throw an exception-Visual Studio automatically adds code to throw an exception for any conversion methods you don't implement.

为了实现System.IConvertible接口,需要添加IConvertible接口到类型定义。然后,使用VS来自动实现这个接口。VS自动建立了17个成员声明,包括每个基本类型都具有的GetTypeCode,ChangeType,和ToType方法。你不必实现每一个方法,例如象ToDateTime这种可能不会被调用的方法。对于这种方法,只需简单的抛出一个异常,不过你不需要自己来实现, VS会自动给每个转换方法添加一个异常抛出代码。

After you implement IConvertible, the custom type can be converted using the standard System.Convert class as shown here:

在你实现了IConvertible后,这个自定义类型就可以使用标准的System.Convert类来进行转换了。

' VB
Dim a As TypeA, b As Boolean
a = 42
' Convert using ToBoolean.
b = Convert.ToBoolean(a)
Console.WriteLine("a = {0}, b = {1}", a.ToString, b.ToString)
 
// C#
TypeA a; bool b;
a = 42;
// Convert using ToBoolean.
b = Convert.ToBoolean(a);
Console.WriteLine("a = {0}, b = {1}", a.ToString(), b.ToString());

Lab: Safely Performing Conversions练习:安全的执行转换

The following exercises show how to avoid problems with implicit conversions so that your programs function predictably. If you encounter a problem completing an exercise, the completed projects are available on the companion CD in the Code folder.

下面练习将示范如何避免隐式转换时产生的问题。

Exercise 1: Examine Implicit Conversion 练习1:考察隐式转换

In this exercise, you will examine conversion to determine which number types allow implicit conversion.

在这个练习中,你将考察并确定哪几个number类型允许隐式转换。

1.    Create a new console application in Visual Studio.

1.在VS中建立一个新的客户端应用程序

2.    Declare instances of three value types: Int16, Int32, and double. The following code sample demonstrates this:

2.声明三个值类型实例:int16,int32,double。

3.           ' VB
4.           Dim i16 As Int16 = 1
5.           Dim i32 As Int32 = 1
6.           Dim db As Decimal = 1
7.            
8.           // C#
9.           Int16 i16 = 1;
10.       Int32 i32 = 1;
11.       double db = 1;

12.Attempt to assign each variable to all the others, as the following code sample demonstrates.

12.尝试去将它们互相赋值

13.       ' VB
14.       i16 = i32
15.       i16 = db
16.        
17.       i32 = i16
18.       i32 = db
19.        
20.       db = i16
21.       db = i32
22.        
23.       // C#
24.       i16 = i32;
25.       i16 = db;
26.        
27.       i32 = i16;
28.       i32 = db;
29.        
30.       db = i16;
31.       db = i32;

32.Attempt to build your project. Which implicit conversions did the compiler allow, and why?

32.尝试编译你的项目。哪几个隐式转换是可以编译的,为什么?

 

 

Exercise 2: Enable Option Strict (Visual Basic Only) 练习2:使用精确选项(只能在VB中使用)

In this exercise, which is only for developers using Visual Basic, you will modify the compiler's options and then rebuild the project you created in Exercise 1.

这个练习只是针对哪些使用VB进行开发的人员,你将修改编译器的选项,然后重新编译你在练习1中建立的项目。

1.    In Visual Studio, open the project you created in Exercise 1.

1.在VS中,打开你在练习1中建立的项目。

2.    Click the Project menu, and then click ProjectName Properties.

2.点击项目菜单,然后点击项目属性。

3.    Click the Compile tab. For Implicit Conversion, change the Notification type to Error.

3.点击“编译”(compile)卡片项。对于隐式转换,改变Notification(通告)选项类型为Error。(sorry,我这没有VS2005,具体显示名称无法确定。)

4.    Attempt to build your project. Which implicit conversions did the compiler allow, and why?

4.尝试编译你的项目。查看哪几个隐式转换是可以编译的,为什么?

 

 

Lesson Summary本课摘要

·         The .NET Framework can automatically convert between built-in types. Widening conversions occur implicitly in both Visual Basic and C#. Narrowing conversions require explicit conversion in C#, while Visual Basic allows narrowing conversions by default.

·         .net框架能够自动在默认类型之间进行转换。

·         Boxing allows any type to be treated as a reference type.

·         装箱允许任意类型被加工为引用类型。

·         You must specifically implement conversion operators to enable conversion in custom types.

·         你必须实现指定的转换操作符,才可以进行自定义类型的转换。

Lesson Review本课回顾

You can use the following questions to test your knowledge of the information in Lesson 4, "Converting Between Types." The questions are also available on the companion CD if you prefer to review them in electronic form.

你可以使用下列问题来测试你在本课学习到的知识。

 

Answers 

Answers to these questions and explanations of why each answer choice is right or wrong are located in the "Answers" section at the end of the book.

回答下列问题并解释每个答案正确或错误的原因。

 

1. 

Why should boxing be avoided? (Choose one.)

为什么要避免装箱?(单选)

A.    It adds overhead.它增加了损耗(成本)

B.    Users must have administrative privileges to run the application.用户必须具有管理权限来允许这个应用程序。

C.    It makes code less readable.它降低了代码可读性。

2. 

Structures inherit ToString from System.Object. Why would someone override that method within a structure? (Choose as many correct answers as apply.)

结构从System.Object继承了ToString方法。为什么在一个结构中要重写这个方法?(多选)

A.    To avoid boxing.避免装箱

B.    To return something other than the type name.返回除了这个类型名称之外的其他信息。

C.    The compiler requires structures to override the ToString method.编译器要求结构重写ToString方法

D.    To avoid run-time errors caused by invalid string conversions.由于这个有问题的字符串转换将导致运行时错误。

3. 

If there is no valid conversion between two types, what should you do when implementing the IConvertible interface?

假设两个类型间的转换无法避免,当实现IConvertible接口时,你要作什么?

A.    Delete the ToType member that performs the conversion.删除ToType成员

B.    Throw an InvalidCastException.抛出一个InvalidCastException异常

C.    Throw a new custom exception reporting the error.抛出一个自定义异常来报告这个错误。

D.    Leave the member body empty.丢弃空的成员。

4. 

With strict conversions enabled, which of the following would allow an implicit conversion? (Choose all that apply.)

在精度转换设置为允许时,下面哪些选项将允许一个隐式转换(多选)

A.    Int16 to Int32

B.    Int32 to Int16

C.    Int16 to Double

D.    Double to Int16

Answers

1. 

Correct Answer: A

A.    Correct: The primary reason to avoid boxing is because it adds overhead.避免装箱的主要原因是它导致增加了成本(损耗)

B.    Incorrect: Boxing requires no special privileges.装箱不需要指定权限

C.    Incorrect: Boxing does not make code less readable.装箱不会降低代码可读性

2. 

Correct Answers: A and B

A.    Correct: Value types are boxed when an abstract method inherited from System.Object is called. Overriding the method avoids boxing.当一个从System.Object类继承的抽象方法被调用时,导致值类型被装箱。重写这个方法可以避免装箱。

B.    Correct: By default, the ToString method simply returns the type name, which is typically not useful for a consuming application.默认情况下,Tostring方法仅返回类型名称,这在实现应用程序时,没有特别的用处。

C.    Incorrect: The compiler does not require structures to override the ToString method.编译器不要求结构重写ToString方法

D.    Incorrect: ToString never causes a run-time error; it simply returns the type name unless overridden.ToString 方法从来没有导致一个运行时错误的产生;没有被重写的ToString仅返回类型名称

3. 

Correct Answer: B

A.    Incorrect: You can't omit a member of an interface and still conform to that interface.你不能忽略任何一个接口的成员,并保持它们和接口中定义的一致性。

B.    Correct: InvalidCastException is the recommended exception to throw.InvalidCastException是被推荐使用的异常。

C.    Incorrect: While you could throw a custom exception, using standard exception types makes it easier for developers writing code to consume your type to catch specific exceptions.你可以抛出一个自定义异常,引用标准异常类型,开发人员可以更容易的编写代码来实现你的类型并捕获指定的异常。

D.    Incorrect: You must return a value for each conversion member.每个转换成员都必须有返回值。

4. 

Correct Answers: A and C

A.    Correct: You can convert from Int16 to Int32 because that is considered a widening conversion. Because Int32 can store any value of Int16, implicit conversion is allowed.可以,因为它是一个拓展转换。(小范围赋给大范围)

B.    Incorrect: You cannot convert from Int32 to Int16 because that is considered a narrowing conversion. Because Int16 cannot store any value of Int32, implicit conversion is not allowed.不可用,因为当前设定了确保精度选项,不可用进行一个截断转换。(大范围赋给小范围)

C.    Correct: You can convert from Int16 to Double because that is considered a widening conversion. Because Double can store any value of Int16, implicit conversion is allowed.可以。原因同A

D.    Incorrect: You cannot convert from Double to Int16 because that is considered a narrowing conversion. Because Int16 cannot store any value of Double, implicit conversion is not allowed.不可用,原因同B

 


 

Chapter Review本章回顾

To further practice and reinforce the skills you learned in this chapter, you can perform the following tasks:

持续的练习和巩固,将保持你在本章学到的东西。你可以完成下列任务。

·         Review the chapter summary.

·         回顾本章摘要

·         Review the list of key terms introduced in this chapter.

·         回顾本章中的关键术语列表

·         Complete the case scenarios. These scenarios set up real-world situations involving the topics of this chapter and ask you to create a solution.

·         完成场景案例。这些场景设置了包括本章的主题在内的真实世界的情况,并要求你建立一个解决方案。

·         Complete the suggested practices.完成建议的练习

·         Take a practice test.完成练习测试

Chapter Summary本章摘要

·         Value types are small variables that store data directly rather than storing a pointer to a second memory location that contains the data. Assignment between value types copies the data from one variable to the other, creating a separate instance of the data. You can make value types nullable using the Nullable generic type, and you can create structures that combine multiple value types.

·         值类型是一种小的变量,它直接存储数据,这种方式比存储一个指向一小片包含数据的内存地址要更好。值类型之间的数据拷贝是将一个变量分配给另一个,这个过程建立的是一个单独的数据实例。利用Nullable泛型类型,你能够判断值类型是否被赋值,并且你能够建立由多种值类型组成的结构。

·         Reference types contain the address of data rather than the actual data. The .NET Framework includes thousands of reference types to perform almost any task you could require. The most commonly used reference type is the String class. Because the String class is immutable, it behaves differently from other reference types: when you copy a string, a unique instance of the data is created. When you copy most reference classes, only the pointer is copied, which means changes made to one instance are also reflected in the other instance. When an unexpected event occurs, the .NET Framework throws an exception. You can handle these exceptions by creating Try/Catch blocks in your code.

·         引用类型包含实际数据的数据地址。Net框架包括数以千计的引用类型用来执行你需要的大部分任务。最常用的引用类型使String类。因为String类是不可变的,它与其他引用类型不同的区别是:当你拷贝一个string,将建立一个唯一的数据实例。当你大量复制引用类型的时候,拷贝的只是指针。这个意思就是:对一个实例的改变将反映到其他的实例。当一个未预料到的事件发生时,net框架抛出一个异常。在你的代码中,通过建立Try/Catch块,你能够处理这些异常。

·         Classes in .NET Framework languages are custom types that can include value types, reference types, methods, attributes, and properties. To enable consistency between classes, you can use inheritance (where you derive a new class from an existing class) or an interface (where you are required to implement specified interfaces). Generics enable you to create a class or method that works with a variety of types. To enable applications to respond to planned events, you can raise and respond to events.

·         类在net框架语言中是自定义类型,它能够包括值类型,引用类型,方法,attributes,和properties。你可以使用继承(从一个已存在的类派生一个新类)或接口(要求实现指定接口)来保持类之间的一致性。泛型可以使你建立一个能够使用多种类型的类或方法。允许应用程序响应计划内事件,你能够触发并响应事件。

·         Conversion enables you to compare and copy values between different types. Implicit conversion happens automatically and behaves differently in Visual Basic and C#. C# allows implicit conversion for only narrowing conversions, where no information could be lost. Visual Basic allows implicit conversion for both narrowing and widening conversions. When values are converted from a value type to a reference type, it is considered boxing. Unboxing occurs if you assign a reference object to a value type.

·         转换允许你在不同类型之间进行值的比较和值的拷贝。隐式转换是自动执行的,并且在VB和C#中有不同的执行情况。C#仅在缩小转换中不会丢失信息时才允许隐式转换。VB在放大转换和缩小转换时都允许隐式转换。当一个值类型转换为一个引用类型时,将会导致装箱。如果你将一个引用类型分配给一个值类型,将导致拆箱的发生。

Key Terms关键术语

Do you know what these key terms mean? You can check your answers by looking up the terms in the glossary at the end of the book.

你知道这些关键术语的意思吗?通过查询书后的术语表,你可以检查你的回答。

·         Boxing装箱

·         Cast造型

·         Constraint约束

·         Contract约定

·         Exception异常

·         filtering exceptions异常过滤

·         garbage collection垃圾收集

·         generic type泛型类型

·         heap堆

·         interface接口

·         narrowing缩小

·         nullable type未分配类型

·         signature签名(出现在代理)

·         stack栈

·         structure结构

·         unboxing拆箱

·         widening加宽

Case Scenario

In the following case scenario, you will apply what you've learned about types. You can find answers to these questions in the "Answers" section at the end of this book.

在下面案例场景中,你将应用你学到的关于类型的知识。你可以在书后的Answers部分查看问题的答案。

Case Scenario: Designing an Application案例场景:设计一个应用程序

You have recently accepted a job as an internal application developer in the information technology department of an enterprise healthcare company. Your first task is to design an internal application that employees will use to manage information about customers (whom everyone calls "subscribers"), their current plans, medications, and chosen doctors. Answer your manager's questions about your design choices.

你最近找到了一份工作,在一个医疗保健公司的企业技术信息部做一名国内应用程序开发人员。你的第一个任务是设计一款面向国内的软件,人们可以使用它来管理消费者(统称为订户)的信息,他们当前的计划安排,药品信息,和他们的医生的信息。回答你上司关于设计选择的问题。

1. 

We need to manage information about both subscribers and doctors. How will you do this? Will you have one class for both, two separate classes, or what?

我们需要管理订户和医生的信息。你打算如何做?你要为它们俩建立一个类,还是两个单独的类,或者有其他什么想法?

2. 

Our employees need to search for groups of subscribers or doctors. For example, if a doctor retires, we need to contact all that doctor's subscribers and assist them in finding a new physician. Similarly, we contact doctors annually to renew their contracts. How can you store a group of subscribers or doctors in your application?

我们的员工需要对订户或医生这两个组进行搜索。例如,假设一名医生退休了,我们需要联系所以与这名医生有关的订户,并帮助他们找到一名新的医生。同样地,我们每年要和医生联系来和他们签新的合同。在你的应用程序中,你打算如何存储订户和医生这两个组。

3. 

One of the tasks your application will perform is generating mailing labels for groups of subscribers or doctors. Is there any way that you can write a single method that will handle addresses for both subscribers and doctors? How will you implement this?

你应用程序的任务之一是为订户或医生组发送邮件。不管怎样,你能够编写一个单独的方法来同时处理订户和医生的地址吗?你打算如何实现它?

4. 

The privacy of our information is extremely important to us. Our database developer is going to restrict permissions on the database to prevent unauthorized users from gaining access. If a user's privileges are rejected, I'd like you to instruct the user to contact their manager to gain access. How will you handle it if a database query is rejected for insufficient privileges?

我们的信息是保密的,这点对我们非常重要。我们的数据库开发人员对数据库权限进行来限制,以防止未被授权的用户从开放端口获得访问。假设一个用户权限不足,我希望你可以联系用户,让他去联系他的管理员。假设数据库查询由于权限不足被拒绝,你要如何处理它?

Answers

1. 

Both subscribers and doctors will have a lot of information in common, including names, phone numbers, and addresses. However, they will each have unique information, also. For example, you need to track the subscription plan and payment information for subscribers. For doctors, you need to track contract details, medical certifications, and specialties. Therefore, you should create separate classes for subscribers and doctors, but derive them from a single class that contains all members shared by both classes. To do this, you could create a base class named Person, and derive both the Subscriber and Doctor classes from Person.

订户和医生这两者之间有大量相同的信息,包括姓名,电话号码,和地址。但是,他们彼此也有自己独有的信息。例如,你需要跟踪订户计划并发送付款信息给用户。对于医生,你需要跟踪合同信息,医学证明和其他专门的信息。因此,你要为订户和医生分别建立单独的类,但他们都派生于同一个类,这个类包含类订户和医生之间所有公共的成员。至于如何做,你可以建立一个Person基类,并让订户和医生这两个类都派生与Person。

2. 

You can use an array to store a group of subscribers.

你可以使用数组来存储订户组。

3. 

Yes, you can use generics to create a method that can accept both subscribers and doctors. To access the information in the base class that both classes share, you would need to make the base class a constraint for the generic method.

可以,你能够建立一个泛型方法,它可以同时接收订户和医生。并访问这两个类都具有的基类的信息,你需要给基类的这个泛型方法添加约束。

4. 

The security error would generate an exception. Therefore, to respond to the exception, you should surround the code in a Try/Catch block. Within the Catch block, you should inform the user that he should contact his manager.

这个安全错误将导致一个异常。因此,为了响应这个异常,你需要将代码放到一个Try/Catch块中。而在Catch块里,你要通知用户,让他去联系他的管理员。

 

Suggested Practices练习建议

To help you successfully master the exam objectives presented in this chapter, complete the following tasks.

为了帮助你成功通过考试目标中涉及本章的内容,请完成下列任务。

Manage Data in a .NET Framework Application by Using .NET Framework 2.0 System Types

通过利用net框架2.0的系统类型,在一个net框架应用程序中管理数据。

For this task, you should complete at least Practices 1 and 2. If you want a better understanding of how generics perform in the real world, complete Practice 3 as well.

这个任务中,你至少要完成练习1和2。如果你想更好的理解在真实世界里泛型是如何执行的,最好完成练习3。

·         Practice 1 Open the last project you created, and add exception handling to your code. Unless performance is a higher priority than reliability, all code outside of value type declarations should be in a Try block.

·         练习1.打开你最后建立的项目,并在你的代码中添加异常处理。除非性能比可靠性更重要,否则除了值类型声明外的所有代码都要放到Try块中。

·         Practice 2 Create a linked-list generic class that enables you to create a chain of different object types.

·         练习2 建立一个泛型类的连接表,它可以使你建立一个区别于Object类型的系列。

·         Practice 3 Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a For loop that uses the class over thousands of iterations. Time the performance of both the generic class and the Object-based class to determine which performs better. You can use DateTime.Now.Ticks to measure the time.

·         练习3 建立两个具有相同功能的类,一个使用泛型,一个使用Object类型。建立一个For循环,反复千次的使用类。泛型类和基于Object类型的类,比较这两者的执行时间来确定哪个更好。你可以使用DateTime.Now.Ticks来计算时间。

Implement .NET Framework Interfaces to Cause Components to Comply with Standard Contracts

使用标准约束来要求组件实现net框架接口。

For this task, you should complete all three practices to gain experience implementing common interfaces with real-world classes and schema.

这次任务,你要完成所有三个练习, 通过使用在真实世界中的类和计划来增加实现公共接口的经验。

·         Practice 1 Create a custom class that implements the necessary interfaces to allow an array of the class to be sorted.

·         练习1 建立一个自定义类,它要实现必要的接口,来允许存储类中的数组。

·         Practice 2 Create a custom class that can be converted to common value types.

·         练习2 建立一个自定义类,它能够被转换为普通的值类型。

·         Practice 3 Create a custom class that can be disposed of using the IDisposable.Dispose method.

·         练习3 建立一个自定义类,可以利用IDisposable.Dispose方法来释放它。

Control Interactions Between .NET Framework Application Components by Using Events and Delegates

利用事件和代理来控制net框架应用程序组件之间的交互。

For this task, you should complete both Practices 1 and 2.

练习1和2都要完成。

·         Practice 1 Open the last Windows Forms application you created, and examine the code Visual Studio automatically generated to respond to user interface events.

·         练习1. 打开你最后建立的windowforms应用程序,并查看VS自动产生的响应用户接口事件的代码。

·         Practice 2 Create a class that throws an event and derives a custom class based on EventArgs. Then create an assembly that responds to the event.

·         练习2 建立一个类,它能够抛出一个事件, 并具有一个派生于EventArgs的自定义类。然后,建立一个程序集,用来响应这个事件。

Take a Practice Test

做一个练习测试

The practice tests on this book's companion CD offer many options. For example, you can test yourself on just the content covered in this chapter, or you can test yourself on all the 70-536 certification exam content. You can set up the test so that it closely simulates the experience of taking a certification exam, or you can set it up in study mode so that you can look at the correct answers and explanations after you answer each question.

在这本书的配套CD中的这个练习测试提供更多的选项,你可以测试自己在70-536认证考试的所有内容。你可以设置它为测试状态,它模拟一个认证考试的环境。或者,将它设为学习模式,在你回答了每个问题后,你可以查看正确答案和原因说明。

 

Practice tests 

For details about all the practice test options available, see the "How to Use the Practice Tests" section in this book's Introduction.

关于所有练习测试选项的详细信息,可以查看本书介绍中的“如何使用练习测试”部分

 

转载于:https://www.cnblogs.com/adsiz/archive/2007/01/06/613519.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值