Chapter 1. C# and the .NET Framework

salmonbrisketΛογισμικό & κατασκευή λογ/κού

2 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

921 εμφανίσεις

Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


1

Chapter 1. C# and the .NET Framework

第一章



.久T
框架

C#
的目标
g潡l
和特点
featu牥s


The goal of C# 2.0 is t o provide a simple, safe, modern, objec t
-
orient ed
(面向对象的)
,
Internet
-
centric, high
-
performance
(高效的)

language for .NET development. C# is now
a fully mature
(成熟的)

l
anguage, and it draws on the lessons learned over the past three
decades. In much the way that you can see in young children the features and
personalities of their parents and grandparents, you can easily see in C# the influence
(影响)

of Java, C++, Visual B
asic (VB), and other languages, but you can also see the
lessons learned since C# was first introduced.

本书的重点
focus


The focus of this book is the C# language and its use as a tool for programming on
the .NET platform, specifically and especially with Visua
l Studio .NET 2005 (full or Express
Edition).

本书中的程序多为控制台程序
console applications


Many of the programs in this book are written as console applications
(控制台程序)
(rather
than as Windows or web applications) to facilitate concentrating on
(关注于)

features of
the l
anguage instead of being distracted by the details of the user interface.

If you are using Mono or other non
-
Microsoft versions of C#, you should find that all of the programs in
this book work just fine, though we have not tested on anything other than th
e Microsoft authorized
version.

本章重点介绍
C#
语言和
.net
平台包括
.net
框架


This c hapt er int roduc es bot h t he C# language and t he .NET plat form, inc ludi ng t he .NET
Framework.

1.1 The .NET Platform

(.net
框架
)

C#

.net
平台的关系:

When Microsoft announced C# in July 2000, its unveiling
(
出现
)

was part of a much larger
event: the announcement of the .NET platform. C# 2.0 represents the maturation of that
Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


2

language and coincides with
(与
..
相符合)

the release of the next generation of tools
for .NET.

什么是
.net platform
:

The .NET plat form is a development framework t hat provides a
new applic at ion
programming int erfac e (API
应用编程接口
) to the services and APIs of classic Windows
operating systems while bringing together a number of disparate technologies that
emerged from Microsoft during the late 1990s. This includes COM+ component servi
ces,
a commit ment
(认可)

to XML and object
-
oriented design, support for new web services
protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet, all integrated
within the Distributed interNet Applications (DNA) architecture.

.net platform
包括三个产品群

p牯duct g牯ups



Microsoft has devoted enormous resources to the development of .NET and its associated
(相关的)

technologies. The results of this commitment to date are impressive
(给人印
象深刻)
. For one thing, the scope
(范围)

of .NET is huge. The platform consists of

three
product groups:



A set of languages, including C# and VB, a set of development tools including
Visual Studio .NET, a comprehensive class library for building web services and
web and Windows applications, as well as the Common Language Runtime (CLR)
to execute objects built within this framework



Two generations of .NET Enterprise Servers: those already released and those to
be released over the next 24
-
36 months



New .NET
-
enabled non
-
PC devices, from cell phones to game boxes

1.
2

The .NET Framework

(.N
ET
框架
)

.NET
的优势和特点


Microsoft .NET supports not only language independence
(
独立
)
, but also language
integration
(集成)
. This means that you can inherit
(继承)

from classes, catch exceptions
(异常)
, and take advantage of polymorphism
(多态)

across different languages. The
.NET
Framework makes this possible with a specification called the
Common

Type

System

(CTS
公共语言运行时
) that all .NET components
(组件)

must obey. For example, everything
in .NET is an object of a specific class that derives from the root class called
System.Objec
t
. The CTS supports the general concept of classes, interfaces, and
delegates (which support callbacks).



注意:此段
CTS
的作用。

Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


3

Additionally, .NET includes a
Common

Language

Specification

(CLS
通用语言规范
), which
provides a series of basic rules that are required for la
nguage integration. The CLS
determines the minimum requirements for being a .NET language. Compilers that
conform to the CLS create objects that can interoperate with one another. The entire
Framework Class Library (FCL) can be used by any language that co
nforms to the CLS.

注意:此段
CL
S
的作用。

.NET
框架
F牡mew潲k
的组件
C潭p潮ents


The .NET Framework sit s on t op of t he operat ing syst em, whic h c an be any flavor
(版本)

of Windows


and c onsist s of a number of c omponent s, c urrent ly inc luding:



Five offic ial languages: C#, VB, Visual C++, Visual J#,
and JSc ript.NET



The CLR, an objec t
-
orient ed plat form for Windows and web development t hat all
t hese languages share



A number of relat ed c lass libraries, c ollec t ively known as t he Framework Class
Library

Figure 1
-
1 breaks down the .NET Framework into its sy
stem architectural
components



Fi gure 1
-
1. NET Framework archi tecture



.NET Framewor
最重要的组件:

The most import ant c omponent of t he .NET Framework is t he CLR, whic h provides t he
envi ronment in whic h programs are exec ut ed. The CLR i nc ludes a virt ual mac hi ne
(
虚拟机
)
,
analogous
(
类似
)

in many ways to the Java virtual machine. At a high level, the CLR
Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


4

activates
(激活)

objects, performs security checks on them, lays them out in memory,
executes them, and garbage
-
collects
(垃圾回收)

them. (The Common Type System is also
part of the CLR.)

Figure 1
-
1
的组成解释:

In Figure 1
-
1, the layer on top of the CLR is a set of fram
ework classes, followed by an
additional layer of data and XML classes, plus another layer of classes intended for web
services, Web Forms, and Windows Forms. Collectively, these classes make up the FCL,
one of the largest class libraries in history and on
e that provides an object
-
oriented API
for all the functionality that the .NET platform encapsulates. With more than 4,000
classes, the FCL facilitates rapid development of desktop, client/server, and other web

services and applications.

FCL
得最底层,框架基类:

The set of Framework base classes, the lowest level of the FCL, is similar to the set of
classes in Java. These classes support input and output, string manipulation
(字符串操作)
,
security management, network communication, thread management
(线程管理)
, te
xt
manipulation, reflection and collections functionality, etc.

支持数据管理和
XML
操作的基类:

Above this level is a tier of classes that extend the base classes to support data
management and XML manipulation. The data classes support persistent management of
data that

is maintained on backend databases. These classes include the Structured
Query Language (SQL) classes to let you manipulate persistent data stores through a
standard SQL interface. The .NET Framework also supports a number of classes to let you
manipulate

XML data and perform XML searching and translations.

W
eb service, web forms and windows forms
组件:

Ext ending t he Framework base c lasses and t he dat a and XML c lasses is a t ier of c lasses
geared t oward building applic at ions using t hree different t ec hnologies: web servic es,
Web Forms, and Windows Forms. Web servic es inc lude a number of c lasses t hat sup
port
t he development of l ight weight dist ri but ed c omponent s, whic h wi l l work even in t he fac e
of firewal ls and NAT soft ware. Bec ause web servic es employ st andard HTTP and SOAP as
underlying c ommunic at ions prot oc ols, t hese c omponent s support Plug and Play ac
ross
c yberspac e.

Web Forms and Windows Forms allow you t o apply Rapi d Appl ic at ion Development (RAD)
t ec hniques t o bui lding web and Windows appl ic at ions. Si mply drag and drop c ont rols ont o
your form, double
-
c lic k a c ont rol, and writ e t he c ode t o respond t o
t he assoc iat ed event.

Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


5

1.
3

Compilation and the MSIL

(编译与
M卉L


.NET
中程序不是编译成可执行文件而是被编译为中间语言:

In .NET, programs aren't compiled int o execut able files; t hey are compiled int o
assemblies t hat consist of
Microsoft

Int ermediat e

Language

(MSIL
微软中间语言
)
instructions,
which the CLR then converts into machine code and executes. The MSIL
(often shortened to IL) files C# produces are nearly identical to the IL files other .NET
languages produce; the platform is language
-
agnostic. A key fact about the CLR is that it
is comm
on: the same runtime supports development in C# as well as in VB.NET.

C# code is compiled into IL when you build your project. The IL is saved in a file on disk.
When you run your program, the IL is compiled again, using the
Just

In

Time

(JIT)
compiler (a
process often called
JITing
). The result is machine code, executed by the
machine's processor.

The standard JIT compiler runs
on

demand
. When a method is called, the JIT compiler
analyzes the IL and produces highly efficient machine code, which runs very f
ast. As the
application runs, compilation happens only as needed, and once JIT
-
compiled, the code is
cached for future use. As .NET applications run, they tend to become faster and faster, as
the already compiled code is reused.

The CLS means that all .NET

languages produce very similar IL code. As a result, objects created in one
language can be accessed and derived from another. Thus it is possible to create a base class in VB.NET
and derive from it in C#.

1.
4

The C# Language



语言)

本节介绍了
C#
的发展、主要特点和在面向对象程
序设计方面的支持

The C# language is disarmingly simple, with only about 80 keywords and a dozen built
-
in
datatypes
(只有大约
80
个关键字和
12
种内置类型)
, but it's highly expressive when it comes
to implementing modern programming concepts. C# includes all the support for
structured
, component
-

based, object
-
oriented programming that you expect of a
modern language built on the shoulders of C++ and Java
(和
c++,java
的关系)
, and now
with Version 2.0, many of the most important missing ingredients, such as generics and
anonymous methods, hav
e been added.

C#
的开发


The C# language was developed by a small team led by two distinguished Microsoft
engineers, Anders Hejlsberg and Scott Wiltamuth. Hejlsberg is also known for creating
Turbo Pascal, a popular language for PC programming, and for leading

the team that
Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


6

designed Borland Delphi, one of the first successful integrated development
environments for client/server programming.

C#
与面向对象语言:

At the heart of any object
-
oriented language is its support for defining and working with
classes. Classes def
ine new types, allowing you to extend the language to better model
the problem you are trying to solve. C# contains keywords for declaring new classes and
their methods and properties, and for implementing encapsulation, inheritance, and
polymorphism, the
three pillars of object
-
oriented programming.

In C#, everything pertaining to a class declaration is found in the declaration itself. C#
class definitions don't require separate header files or Interface Definition Language (IDL)
files. Moreover, C# suppor
ts a new XML style of inline documentation that simplifies the
creation of online and print reference documentation for an application.

C# also supports
interfaces
(接口)
, a means of making a contract with a class for services
that the interface stipulates. I
n C#, a class can inherit from only a single parent, but a
class can implement multiple interfaces. When it implements an interface, a C# class in
effect

promises to provide the functionality the interface specifies.

C# also provides support for
structs
(结构
体)
, a concept whose meaning has changed
significantly from C++. In C#, a struct is a restricted, lightweight type that, when
instantiated, makes fewer demands on the operating system and on memory than a
conventional class does. A struct can't inherit from

a class or be inherited from, but a
struct can implement an interface.

C# provides full support of
delegates

(
委托
)


to provide invocation of methods through
indirection. In other languages, such as C++, you might find similar functionality (as in
pointers
to member functions), but delegates are type
-
safe reference types that
encapsulate methods with specific signatures and return types.

C# provides component
-
oriented features
(基于组件的特征)
, such as properties, events,
and declarative constructs (such as
attribut
es
). Component
-
oriented programming is
supported by the storage of metadata with the code for the class. The metadata describes
the class, including its methods and properties, as well as its security needs and other
attributes, such as whether it can be s
erialized; the code contains the logic necessary to
carry out its functions. A compiled class is thus a self
-
contained unit. Therefore, a hosting
environment that knows how to read a class' metadata and code needs no other

information to make use of it. Us
ing C# and the CLR, it is possible to add custom
metadata to a class by creating custom attributes. Likewise, it is possible to read class
metadata using CLR types that support reflection.

程序集
Assembly


Chapter 1. C# and the .NET F
ramework

第一章

C#


.NET
框架


7

When you compile your code you create an assembly. An
assembly

is a collection of files
that appear to the programmer to be a single dynamic link library (DLL) or executable
(EXE). In .NET, an assembly is the basic unit of reuse, versioning, security, and
deployment. The CLR provides a number of classes for m
anipulating assemblies.

A final note about C# is that it also provides support for
(最后注意
C#
还支持以下内容)
:



Directly accessing memory using C++ style pointers



Keywords for bracketing such operations as unsafe



Warning the CLR garbage collector not to collect objects referenced by pointers
until they are released

Review Questions
复习题

1.

what is .net p
latform?

2.

what is .net framework?

3.

what is FCL and CLR ?












Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


8

Chapter 2. Getting Started: "Hello World"

第二章

出发:“
He汬o Wor汤


W
hy begin from

Hello World


?
为什么从“
Hell漠坯牬d
”开始?

It is a t i me
-
honored t radit ion t o st art a programmi ng book wit h a "Hel lo Wo
rld" program.
In t his c hapt er, we c reat e, c ompi le, and run a si mple "Hel lo Worl d" program writ t en in C#.
The analysis of t his brief program will int roduc e key feat ures of t he C# language.

Example 2
-
1

illust rat es t he fundament al element s of a very element ar
y C# program.

Example 2
-
1. A simple "Hello World" program in C#

class Hello

{


static void Main( )


{


// Use the system console object


System.Console.WriteLine("Hello World");


}

}

Compiling and running this code displays the words

"Hello World" at the console.
Before we compile and run it, let's first take a closer look at this simple program.

2.1. Classes, Objects, and Types
类、对象和类型

What is type?

The essence of object
-
orient ed programming is t he creat ion of new t ypes. A
t ype

repres
ent s a t hing. Somet imes t he t hing is abst ract, such as a dat a t able or a t hread;
somet imes it is more t angible, such as a but t on in a window. A t ype defines t he t hing's
general propert ies and behaviors.

If your program uses t hree inst ances of a but t on t ype

in a windowsay, an OK, a Cancel,
and a Hel p but t oneach butt on will have a size, t hough t he specific size of each butt on may
differ. Similarly, all t he but t ons will have t he same behaviors (draw, click), t hough how
t hey act ually i mplement t hese behaviors m
ay vary. Thus, t he det ails might differ among
t he individual but t ons, but t hey are all of t he same t ype.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


9

As in many object
-
oriented programming languages, in C# a type is defined by a
class
,
while the individual instances of that class are known as
objects
. Later chapters explain
that there are other types in C# besides classes, including enums, structs, and delegates,
but for now the focus is on classes.

H
ow to define a c# type?
如何定义

类型

The "Hello World" program declares a single type: the
Hello

class. To define a C# type,
you declare it as a class using the
class

keyword, give it a name

in this case,
Hello

and
then define its properties and behaviors. The property and behavior d
efinitions of a C#
class must be enclosed by open and closed braces (
{}
).

2.1.1. Methods
方法

A class has both properties and behaviors
(一个类包括属性和行为)
. Behaviors are defined
with member methods; properties are discussed in
Chapter 3
.

H
ow to use the method?

A
met
hod

is a
function

owned by your class
(方法是类所拥有的函数)
. In fact, member
methods are sometimes called
member

functions
. The member methods define what
your class can do or how it behaves. Typically, methods are given action names, such as
WriteLine( )

or
AddNumb
ers( )
. In the case shown here, however, the class method has
a special name,
Main( )
, which doesn't describe an action but does designate to the CLR
that this is the main, or first method, for your class.

注意:当你的程序运行时
CLR

Main
()作为你程序的入口进行调用。

The CLR c alls
M
ain()

when your program starts.
Main()

is the entry point for your
program, and every C# program must have a
Main( )

method.
[1]

[1]

It's techni cal ly possi bl e to have multiple
Main( )

methods i n C#; i n that ca
se you use the
/main

command
-
l ine swi tch to tell
C# whi ch cl ass contai ns the
Main( )

method that shoul d serve as the entry poi nt to the program

方法的声明是一种创立者和使用者之间的协议。

Method declarations are a contract between the creator of the method and the consumer
(user) of the method. It is likely that the creator and consumer of the method will be the
same programmer, but this doesn't have to be so: it is po
ssible that one member of a
development team will create the method and another programmer will use it.

To declare a method, you specify a return value type followed by a name. Method

declarations also require parentheses, whether the method accepts parame
ters or not.
For example:

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


10

int myMethod(int size)

declares a method named
myMethod()

that takes one parameter: an integer that will be
referred to within the method as
size
. This method returns an integer value. The return
value type tells the consumer of t
he method what kind of data the method will return
when it finishes running.

Some methods don't return a value at all; these are said to return
void
, which is specified
by the
void

keyword. For example:

void myVoidMethod();

declares a method that returns
v
oid

and takes no parameters. In C# you must always
declare a return type or
void
.

2.1.2. Comments

注释

A C# program can also cont ain comment s. Take a look at t he first line aft er t he opening
brace of t he main met hod shown earlier:

// Use the system console object

什么是注释

The text begins with two forward slash marks (
//
). These designate
(代表)

a
comment
.
A c
omment is a note to the programmer and doesn't affect how the program runs. C#
supports three types of comments.

第一类注释:单行注释

C++
风格

The first t ype, just shown, indic at es t hat all t ext t o t he right of t he c omment mark is t o be
c onsidered a c omment, unt il t he
end of t hat li ne. This is known as a
C++

st yle

c omment
.

第二类注释:多行注释,
C
风格

The second type of comment, known as a
C
-
style

comment
, begins with an open
comment mark (
/*
) and ends with a closed comment mark (
*/
). This allows comments to
span more than one line w
ithout having to have
//

characters at the beginning of each
comment line, as shown in
Example 2
-
2
.

Example 2
-
2. Illustrating multiline comments

namespace HelloWorld

{

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


11


class HelloWorld


{


static void Main( )


{


/* Use the
system console object


as explained in the text */


System.Console.WriteLine("Hello World");


}


}

}

While you can't nest C++ style comments, it is possible to nest C++ style comments
within C
-
style comments. For this rea
son, it is common to use C++ style comments
whenever possible, and to reserve the C
-
style comments for "commenting
-
out" blocks of
code.

2.1.3. Console Applications
控制台程序

什么是控制台程序


"Hello World" is an example of a
console

program. A console application typic
ally has no
graphical user interface (GUI); there are no list boxes, buttons, windows, and so forth.
Text input and output are handled through the standard console (typically a command or
DOS window on your PC). Sticking to console applications for now hel
ps simplify the early
examples in this book, and keeps the focus on the language itself. In later chapters, we'll
turn our attention to Windows and web applications, and at that time we'll focus on the
Visual Studio .NET GUI design tools.

控制台中的输出方法
WriteLine( )

All that the
Main()

method does in this simple example is write the text "Hello World" to
the
standard output

(typically a command prompt window). Standard output is managed
by an object named
Console
. This
Console

object has a method

called
WriteLine( )

that
takes a
string

(a set of characters) and writes it to the standard output. When you run this
program, a command or DOS screen will pop up on your computer monitor and display
the words "Hello World."

点操作符

You invoke a met hod wit h
t he dot operat or (.). Thus, t o c all t he
Console

object's
WriteLine()

method, you write
Console.WriteLine(
...
)
, filling in the string to be
printed.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


12

2.1.4. Namespaces
命名空间

为什么需要命名空间?

Console

is only one of a tremendous number of useful types that are part of

the .NET FCL.
Each class has a name, and thus the FCL contains thousands of names

FCL
包含成千上
万的名字)
, such as
ArrayList
,
Hashtable
,
FileDialog
,
DataException
,
EventArgs
, and
so on. There are hundreds, thousands, even tens of thousands of names.

This presents a

problem. No developer can possibly memorize all the names that the .NET

Framework uses, and sooner or later you are likely to create an object and give it a name
that has already been used. What will happen if you purchase a
Hashtable

class from
another v
endor, only to discover that it conflicts with the
Hashtable

class that .NET
provides? Remember, each class in C# must have a unique name and you typically can't
rename classes in a vendor's code!

如何解决名字冲突问题?

The solution to this problem is the use of
namespaces
. A namespace restricts a name's
scope, making it meaningful only within the defined namespace.

Assume that I tell you that Jim is an engineer. The word "engineer" is used for many
things in
English, and can cause confusion. Does he design buildings? Write software?
Run a train?

In English I might clarify by saying "he's a scientist

engineer
," or "he's a train engineer."
A C# programmer could tell you that Jim is a
science.engineer

rather than

a
TRain.engineer
. The namespace (in this case,
science

or
train
) restricts the scope of
the word that follows. It creates a "space" in which that name is meaningful.

Further, it might happen that Jim is not just any kind of
science.engineer
. Perhaps Jim
g
raduated from MIT with a degree in software engineering, not civil engineering (are
civil

engineers especially polite?). Thus, the object that is
Jim

might be defined more
specifically as a
science.software.engineer
. This classification implies that the
na
mespace
software

is meaningful within the namespace
science
, and that
engineer

in
this context is meaningful within the namespace
software
. If later you learn that
Charlotte is a
transportation.train.engineer
, you will not be confused as to what
kind of en
gineer she is. The two uses of
engineer

can coexist, each within its own
namespace.

Similarly, if it turns out that .NET has a
Hashtable

class within its
System.Collections

namespace, and that I have also created a
Hashtable

class within a
ProgCSharp.DataS
tructures

namespace, there is no conflict because each exists in its
own namespace.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


13

In
Example 2
-
1
, the
Console

class' name is identified as being in the
System

namespace
by using the code:

System.Console.WriteLine();

2.1.5. The Dot Operator (.)
点操作符

点操作符的作用

In
Example 2
-
1
, the dot operator (.) is used both to access a method (and data) in a class
(in this case, the method
WriteLine( )
), and to restrict the class name to a specific
namespace (in this case, to locate
Console

within the
System

names
pace). This works
well because in both cases we are "drilling down" to find the exact thing we want. The top
level is the
System

namespace (which contains all the
System

objects that the FCL
provides); the
Console

type exists within that namespace, and the

WriteLine()

method
is a member function of the
Console

type.

子空间
subspaces

In many c ases, namespac es are divided int o subspac es. For example, t he
System

namespace contains a number of subnamespaces such as
Data
,
Configuration
,
Collections
, and so forth, while the
Collections

namespace itself is divided into
multiple
subnamespaces.

Namespaces can help you organize and compart mentalize your types. When you write a
complex C# program, you might want to create your own namespace hierarchy, and
there is no limit to how deep this hierarchy can be. The goal of namespaces is
to help you
divide and conquer the complexity of your object hierarchy.

2.1.6. The using Keyword


畳楮u
关键字


U
sing
关键字解决什么问题?

Rather than writing the word
System

before
Console
, you could specify that you will be
using types from the
System

namespace by writing the directive:using System;

at the top of the listing, as shown in
Example 2
-
3
.

Example 2
-
3.
The using keyword

using System;

class Hello

{

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


14


static void Main( )


{


//Console from the System namespace


Console.WriteLine("Hello World");


}

}

Notice the
using

System

directive is placed before the
Hello

class definition. Visual
Studio .NET 2005 defaults to including three
using

statements in every console

application (
System
,
System.Collections.Generic
,
System.Text
).

Although you can designate that you are using the
System

namespace, you can't
designate that you are using the
Sys
tem.Console

object, as you can with some
languages.
Example 2
-
4

won't compile.

Example 2
-
4. Code that doesn't compile (not legal C#
不合法的



)

using System.Console;

class Hello

{


static void Main( )


{


//Console from the System namespace



WriteLine("Hello World");


}

}

This generates the compile error
(编译出现错误)
:

error CS0138: A using namespace directive can only be applied

to namespaces; 'System.Console' is a type not a namespace

If you are using Visual Studio, you will know that you've

made a mistake, because when
you type
usingSystem

followed by the dot, Visual Studio .NET 2005 will provide a list of
valid namespaces, and
Console

won't be among them.

使用
using
语句的小技巧:

The
using

keyword can save a great deal of typing, but it can undermine

the advantages
of namespaces by polluting the scope with many undifferentiated names. A common
solution is to use the
using

keyword with the built
-
in namespaces and with your own
corporate namespaces, but perhaps not with third
-
party components.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


15

Some prog
ramming groups make it a policy to spell out the entire namespace path to the
object (e.g.,
System.Console.WriteLine( )

and not
Console.WriteLine()
) as a form
of documentation. This can become unworkable pretty quickly with deeply nested
namespaces.

2.1.7.

Case Sensitivity
大小写敏感

C# is case
-
sensitive, which means that
writeLine

is not the same as
WriteLine
, which
in turn is not the same as
WRITELINE
. Unfortunately, unlike in VB, the C# development
environment will not fix your case mistakes; if you write the
same word twice with
different cases, you might introduce a tricky
-
to
-
find bug into your program.

A handy trick is to hover over a name that is correct in all but case and then hit
Ctrl
-
Space. The Autocomplete feature of Intellisense will fix the case for
you.

Camel
命名习惯和
Pascal
命名习惯

To prevent suc h a t ime
-
wast ing and energy
-
deplet ing mist ake, you should develop
c onvent ions for naming your variables, func t ions, c onst ant s, et c. The c onvent ion in t his
book is t o name variables wit h c amel not at ion (e.g.,
someVariableName
),

and to name
functions, constants, and properties with Pascal notation (e.g.,
SomeFunction
).

The only difference between camel and Pascal notation is that in Pascal notation,
names begin with an uppercase letter.Microsoft has developed code style guideline
s
that make a very good starting point (and often are all you need). You can download
them from:

http://msdn.microsoft.com/library/default.asp?url=/library/en
-
us/cpgenref/ht ml/cpc
onNETFrameworkDesignGuidelines.asp

2.1.8. The static Keyword


獴慴楣
静态
关键字)

The
Main( )

method shown in
Example 2
-
1

has one more designation. Just before the
return type declaration
void

(which, you will remember, indicates that the method
doesn't return a value) you'll find the keyword
static
:static void Main()

S
ta
tic
关键字的含义

The
static

keyword indicates that you can invoke
Main( )

without first creating an
object of type
Hello
. This somewhat complex issue will be considered in much greater
detail in subsequent chapters. One of the problems with learning a new compute
r
language is you must use some of the advanced features before you fully understand
Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


16

them. For now, you can treat the declaration of the
Main( )

method as tantamount to
magic.

2.2. Developing "Hello World"

开发“
Hello Worl
d


两种方式输入,编译和运行本书中的
C#
程序

Visual Studi
漠.NET
集成
开发


IDE
和记事本

There are at least t wo ways t o ent er, c ompile, and run t he programs in t his book: use t he
Visual St udio .NET Int egrat ed Development Envi ronment (IDE), or use a t ext edit or and
a c ommand
-
line c ompiler (along wit h some addit ional c ommand
-
line t ools t o be
int roduc ed lat er).

Alt hough you
c an

develop soft ware out side Visual St udio .NET, t he IDE provides
enormous advant ages. These inc lude indent at ion support, Int ell isense word c omplet ion,

c olor c oding, and int egrat ion wit h t he help files. Most

import ant, t he IDE inc ludes a
powerful debugger and a wealt h of ot her t ools.

This book t ac it ly assumes t hat you'll be usi ng Vis ual St udio .NET. However, t he t ut orials
foc us more on t he language and t he plat form t han on t he t ools. You c an c opy all t he
exam
ples int o a t ext edit or suc h as Windows Not epad or Emac s, save t hem as t ext files
wit h t he ext ension
.c s
, and c ompile t hem wit h t he C# c ommand
-
line c ompiler t hat is
dist ribut ed wit h t he .NET Framework SDK (or a .NET
-
c ompat ible development t oolc hain
suc h as

Mono or Mic rosoft's Shared Sourc e CLI). Not e t hat some examples in lat er
c hapt ers use Visual St udio .NET t ools for c reat ing Windows Forms and Web Forms, but
even t hese you c an writ e by hand i n Not epad if you are det ermi ned t o do t hings t he hard
way.

2.2.1
. Editing "Hello World"

编辑
"䡥汬漠坯牬W"

To create the "Hello World" program in the IDE, select Visual Studio .NET from your Start
menu or a desktop icon, and then choose File

New

Project from the menu toolbar.
This will invoke the New Project window. (If you are using Visual Studio for th
e first time,
the New Project window might appear without further prompt ing.)
Figure 2
-
1

shows the
New Project window.

Figure 2
-
1. Creating a C# console application in Visual Studio .NET

(在
Visual Studi.NET
中创立

控制台应用程序)

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


17


To open your application, select Visual C# in the Project Types window, and choose
Console Application in the Templates window (if you use the Express Edition of Visual C#,
you don't need to perform that first step; go dir
ectly to the Console Application).

You can now enter a name for the project and select a directory in which to store your files.
Click OK, and a new window will appear in which you can enter the code in
Example 2
-
1
,
as shown in
Figure 2
-
2
.

Figure 2
-
2. The
editor, opened to your new project


Notice that Visual Studio .NET creates a namespace based on the project name you've
provided (
HelloWorld
), and adds a
using

directive for
System
,
Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


18

System.Collections.Generic
, and
System.Text

because nearly every program
you
write will need types from those namespaces.

Visual Studio .NET creates a class named
Program
, which you are free to rename. When
you rename the class, it's a good idea to rename the file as well (
Class1.cs
). If you
rename the file, Visual Studio will
automatically rename the class for you. To reproduce
Example 2
-
1
, for instance, rename the
Program.cs

file (listed in the Solution Explorer
window) to
hello.cs

and change the name of
Program

to
HelloWorld

(if you do this in the
reverse order, Visual Studio

will rename the class to
hello
).

Finally, Visual Studio 2005 creates a program skeleton to get you started. To reproduce
Example 2
-
1
, remove the arguments (
string[]

args
) from the
Main( )

method. Then
copy the following two lines into the body of
Main()
:

// Use the system console object

System.Console.WriteLine("Hello World");

If you aren't using Visual Studio .NET, open Notepad, type in the code from
Example 2
-
1
,
and save the file as a text file named
hello.cs
.

2.2.2. Compiling and Running "Hello World"

编译和运行程序

There are many ways to compile and run the "Hello World" program from within Visual

Studio. Typically you can accomplish every task by choosing commands from the Visual
Studio menu toolbar, by using buttons, and, in many cases, by using key
-
combina
tion
shortcuts.

Keyboard shortcuts can be set by going to Tools

Options

Keyboard. This
book assumes you have chosen the default settings.

Figure 2
-
3. Build toolbar
编译工具条


To run t he "Hello World" program wit hout t he debugger, you c an press Ct rl
-
F5 on your
keyboard, c hoose Debug

St art Wit hout Debugging from
t he IDE menu t oolbar, or
press t he St art Wit hout Debugging but t on on t he IDE Build t oolbar, as shown in
Figure
2
-
4

(you may need t o c ust omize your t oolbar t o make t his but t on available). You c an run
t he program wit hout first explic it ly building it; dependi
ng on how your opt ions are set
(Tools

Opt ions), t he IDE wi ll save t he f ile, buil d it, and run it, possi bly as king you for
permission at eac h st ep
.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


19

Figure 2
-
4. Start Without Debugging button
不调试运行按钮


I st rongly rec ommend t hat you spend some t ime exploring t he Visual St udio 2005
development environment. This is your princ ipal t ool as a .NET developer, and you
want t o learn t o use it wel l. Ti me invest
ed up front i n get t ing c omfort able wit h Visual
St udio will pay for it self many t imes over in t he c oming mont hs. Go ahead, put t he
book down and look at it. I'll wait for you.

编译和运行“
Hello World
”程序的步骤

Use t he following st eps t o c ompile and run t he "Hello Wor
ld" program using t he C#
c ommand
-
line c ompiler t hat c omes wit h t he .NET Framework SDK, Mono, or Shared
Sourc e CLI (
ht t p://msdn.mic rosoft.c om/net/ssc li/
):

1.

Save
Example 2
-
1

as the file
hello.cs
.

2.

Open a .NET command window (Start

Programs

Visual Studio .NET

Visual Studio Tools

Visual Studio Command Prompt. If you're on Unix,
you

should start at a text console, xterm, or something that gives you a shell prompt.

3.

From the command line, use this command if you are using the .NET or Shared
Source CLI C# compiler:csc /debug hello.cs

4.

Use this command if you are using Mono:mcs
-
debug
hello.cs

5.

This step builds the EXE file. If the program contains errors, the compiler reports
them in the command window. The
/debug

command
-
line switch inserts symbols
in the code so that you can run the EXE under a debugger or see line numbers in
stack tr
aces. (You'll get a stack trace if your program generates an error that you
don't handle.)

6.

To run the program under .NET, enter:hello

7.

Use this command with the Shared Source CLI:clix hello.exe

8.

and this command with Mono:mono hello.exe

You should now see th
e venerable words "Hello World" appear in your command window.

Just in Time Compilation
即时编译

Compiling
hello.cs

using
csc

creates an EXE file. Keep in mind, however, that the
.exe

file
contains op
-
codes written in MSIL, which is introduced in
Chapter 1
.

Int
erestingly, if you write this application in VB.NET or any other language compliant with
the .NET CLS, you will have compiled it into more or less the same MSIL. By design, IL
code created from different languages is virtually indistinguishable.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


20

In additio
n to producing the IL code (which is similar in spirit to Java's bytecode), the
compiler creates a read
-
only segment of the
.exe

file in which it inserts a standard Win32
executable header. The compiler designates an entry point within the read
-
only segmen
t;
the operating system loader jumps to that entry point when you run the program, just as
it would for any Windows program.

The operating system can't execute the IL code, however, and that entry point does
nothing but jump to the .NET JIT compiler (also
introduced in
Chapter 1
). The JIT
produces native CPU instructions, as you might find in a normal
.exe
. The key feature of
a JIT compiler, however, is that functions are compiled only as they are used, just in time
for execution.

2.3. Using the Visual Stud
io .NET Debugger
使用
.NET
调试器

Arguably, the single most important tool in any development environment is the
debugger. The Visual Studio debugger is very powerful and it will be well worth whatever
time you put into learning how to use it well. That said, the
fundamentals of debugging
are very simple. The three key skills are:



How to set a breakpoint and how to run to that breakpoint



How to step into and over method calls



How to examine and modify the value of variables, member data, and so forth

This chapter d
oesn't reiterate the entire debugger documentation, but these skills are so
fundamental that it does provide a crash (pardon the expression) course.

The debugger can accomplish the same thing in many ways, typically via menu choices,
buttons, and so forth.

The simplest way to set a breakpoint is to click in the left margin.
The IDE marks your breakpoint with a red dot, as shown in
Figure 2
-
5
.

Figure 2
-
5. A breakpoint

断点


To run t he debugger, you c an c hoose Debu
g

St art or just press F5. The program t hen
c ompi les and runs t o t he breakpoi nt, at whic h t i me it st ops, and a yel low arrow i ndic at es
t he next st a
t ement for exec ut ion, as in
Figure 2
-
6
.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


21

Figure 2
-
6. The breakpoint hit

断点处


Aft er you've hit your breakpoint it is easy t o examine t he values of various objec t s. For
example, you c an find t he value of t he variable
i

just by put t ing t he c ursor over it and
wait ing a moment, as shown in
Figure 2
-
7
.

Figure 2
-
7. Showing a value


示值


The debugger IDE also provides a number of useful windows, suc h as a Loc als window
t hat displays t he values of all t he loc al variables (see
Figure 2
-
8
).

Figure 2
-
8. Locals window
本地窗口


Int rins ic t ypes suc h

as int egers si mply show t heir value (see
i

earlier), but object s show
t heir t ype and have a plus (
+
) sign. You c an expand t hese objec t s t o see t heir int ernal
dat a, as shown in
Figure 2
-
9
. You'll learn more about objec t s and t heir int ernal dat a in
upc oming

c hapt ers.

Chapter2.Getting started:

Hello World


第二章

从“
Hello World
”开始


22

Figure 2
-
9. Locals window object expanded


You can step into the next method by pressing F11. Doing so steps into the
DrawWindow( )

method of the
Window

class, as shown in
Figure 2
-
10
.

Figure 2
-
10. Stepping into a method


You can see that the
next execution statement is now
WriteLine( )

in
DrawWindow( )
.
The Autos window has updated to show the current state of the objects.

There is much more to learn about the debugger, but this brief introduction should get
you started. You can answer many pr
ogramming questions by writing short
demonstration programs and examining them in the debugger. A good debugger is, in
some ways, the single most powerful teaching tool for a programming language.

R
eview questions

1

analyze the component of the

Hello World


program.

2

H
ow can edit and compile c# programs?

3.
Instead of printing "
Hello World
!" as the last text on the command co
nsole before the
program finishes, change the source code so that the program writes "Bye Bye. Have a
good day!"

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


23

Chapter 3. C# Language Fundamentals

第三章


语言基础

Chapter 2

demonstrated a very simple C# program. Nonetheless
(尽管如此)
, that little
program was co
mplex enough that I had to skip some of the pertinent
(相关的)

details.
This chapter illuminates
(阐释)

these details by delving
(探究)

more deeply into the syntax
(语法)
and structure of the C# language itself.

本章的主要内容:

This chapter discusses the type system in C#, dr
awing a distinction between built
-
in
types (
int
,
bool
, etc.) versus user
-
defined types (types you create as classes and
interfaces). The chapter also
c
overs programming fundamentals such as how to create
and use variables and constants. It then goes on to
introduce enumerations, strings,
identifiers, expressions, and statements.

The second part of the chapter explains and demonstrates the use of flow control
statements, using the
if
,
switch
,
while
,
do...while
,
for
, and
foreach

statements.
Also discussed are

operators, including the assignment, logical, relational, and
mathematical operators. This is followed by an introduction to namespaces and a short
tutorial on the C# precompiler.

本章讲解基础知识的必要性:

Although C# is principally concerned with the creation and ma
nipulation of objects, it is
best to start with the fundamental building blocks: the elements from which objects are
created. These include the built
-
in types that are an intrinsic part of the C# language as
well as the syntactic elements of C#.

3.1. Types
类型

C
#
是一种强类型语言,什么意思?

C# is a st rongly t yped language. In a st rongly t yped language you must declare t he t ype
of each object you creat e (e.g., int egers, float s, st rings, windows, but t ons, etc.), and t he
compiler will help you prevent bugs by enforcing t hat o
nly dat a of t he right t ype is
assigned t o t hose object s. The t ype of an object signals t o t he compiler t he size of t hat
object (e.g.,
int

indicates an object of 4 bytes) and its capabilities (e.g., buttons can be
drawn, pressed, and so forth).

C#
的两种类型:语言提供
的内置类型和用户在程序中自定义的类型

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


24

Like C++ and Java, C# divides types into two sets:
intrinsic

(built
-
in) types that the
language offers and
user
-
defined

types that the programmer defines.

还有一种分类角度:值类型和引用类型
。它们的区别在哪里?

C# also divides the set of types into two other catego
ries:
value

types and
reference

types.
[1]

The principal difference between value and reference types is the manner in
which their values are stored in memory. A value type holds its actual value in memory
all
ocated on the stack (or it is allocated as part of a larger reference type object). The
address of a reference type variable sits on the stack, but the actual object is stored on
the heap.

注意以下注释,回答:所有的内置类型都是值类型对吗?

[1]

Al l the i ntri nsi c types are val ue types except for
Object

(di scussed i n
Chapter 5
) and
String

(di scussed i n
Chapter 10
). Al l
user
-
defi ned types are reference types except for structs (di scussed i n
Chapter 7
) and enumerated typ
es (di scussed i n
Chapter 3
).

If you have a very large object, putting it on the heap has many advantages.
Chapter 4

discusses the various advantages and disadvantages of working with reference
types; the
current chapter focuses on the intrinsic value types available in C#.

In C#, the size and format of the storage for different intrinsic types (e.g., int) are
platform
-
independent and consistent across all .NET languages.

C# also supports C++ sty
le
pointer

types, but these are used only when working with
unmanaged code. Unmanaged code is created outside of the .NET platform
.

3.1.1. Working with Built
-
in Types

使用
内置类型

The C# language offers t he usual cornucopia
(丰富的)

of intrinsic (built
-
in) types one

expects in a modern language, each of which maps to an underlying type supported by
the .NET CLS. Mapping the C# primitive types to the underlying .NET type ensures that
objects created in C# can be used interchangeably with objects created in any other
l
anguage compliant with the .NET CLS, such as VB.NET.

Each type has a specific and unchanging size. Unlike with C++, a C#
int

is always 4
bytes because it maps to an
Int32

in the .NET CLS.
Table 3
-
1

lists the built
-
in value types
offered by C#.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


25

Table 3
-
1.
C# built
-
in value types
常见的内置值类型

Type

Size (in
bytes)

.NET
type

Description

byte

1

Byte

Unsigned (values 0
-
255).

char

2

Char

Unicode characters.

bool

1

Boolean

True or false.

sbyte

1

SByte

Signed (values
-
128 to 127).

short

2

Int16

Signed (short) (val
ues
-
32,768 to 32,767).

ushort

2

UInt16

Unsigned (short) (values 0 to 65,535).

int

4

Int32

Signed integer values between
-
2,147,483,648 and
2,147,483,647.

uint

4

UInt32

Unsigned integer values between 0 and 4,294,967,295.

float

4

Single

Floating
-
point
number. Holds the values from
approximately +/
-
1.5 * 10
-
45

t o approximat ely +/
-
3.4 *
10
38

wit h seven signif ic ant f igures.

double

8

Double

Double
-
precision floating point. Holds the values from
approximately +/
-
5.0 * 10
-
324

to approximately +/
-
1.8 *
10
308

wit h 15
-
16 signif ic ant f igures.

decimal

16

Decimal

Fixed
-
precision up to 28 digits and the position of the
decimal point. This is typically used in financial
calculations. Requires the suffix "m" or "M."

long

8

Int64

Signed integers from
-
9,223,372,036,8
54,775,808 to
9,223,372,036,854,775,807.

ulong

8

UInt64

Unsigned integers ranging from 0 to 0xffffffffffffffff.

In addition to these primitive types, C# has two other value types:
enum

(considered later
in this chapter) and
struct

(see
Chapter 4
).
Chapte
r 4

also discusses other subtleties
(细
微)

of value types, such as forcing value types to act as reference types through a
process known as
boxing
, and that value types don't "inherit."

The Stack and the Heap
栈和堆

什么是栈及栈的应用?
什么是堆及堆的应用?

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


26

A
stack

is a data structur
e used to store items on a last
-
in first
-
out basis (like a stack of
dishes at the buffet line in a restaurant).
The

stack refers to an area of memory supported
by the processor, on which the local variables are stored.

In C#, value types (e.g., integers) a
re allocated on the stack

an area of

memory is set
aside for their value

and this area is referred to by the name of the variable.

Reference types (e.g., objects) are allocated on the
heap
. The heap is an area of memory
used to allocate space for objects.W
hen an object is allocated on the heap, its address is
returned, and that address is assigned to a reference.

Objects on the stack are destroyed when they go out of scope. Typically a stack frame is
defined by a function. Thus, if you declare a local varia
ble within a function (as explained
later in this chapter), the objects you place on the stack within that function will be
destroyed when the function ends.

Objects on the heap are garbage
-
collected sometime after the final reference to them is
destroyed.

3.1.1.1 Choosing a built
-
in type
选择内置类型

为什么要选择不同内置类型应用?

Typically you decide which size integer to use (
short

,
int
, or
long
) based on the
magnitude of the value you want to store. For example, a
ushort

can only hold values
from 0 through 65,535, while a
u
int

can hold values from 0 through 4,294,967,295.

That said, memory is fairly cheap, and programmer time is increasingly expensive; most
of the time you'll simply declare your variables to be of type
int
, unless there is a good
reason to do otherwise.

Inte
gers are often faster than smaller types because modern CPUs are optimized for
dealing with them. Further, because of padding inserted for alignment, there's often no
space gain to be had from smaller datatypes.

Float

,
double
, and
decimal

offer varying de
grees of size and precision. For most small
fractional numbers,
float

is fine. Note that the compiler assumes that any number with
a decimal point is a double unless you tell it otherwise. To assign a literal
float
, follow the
number with the letter
f

(ass
igning values to literals is

discussed in detail later in this
chapter):

float someFloat = 57f;

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


27

The
char

type represents a Unicode character.
char

literals can be simple, Unicode, or
escape characters enclosed by single quote marks. For example,
A

is a sim
ple character
while
\
u0041

is a Unicode character. Escape characters are special two
-
character tokens
in which the first character is a backslash. For example,
\
t

is a horizontal tab. The
common escape characters are shown in
Table 3
-
2
.

Table 3
-
2. Common e
scape characters
常见的转义符

Char

Meaning

\
'

Single quote

\
"

Double quote

\
\

Backslash

\
0

Null

\
a

Alert

\
b

Backspace

\
f

Form feed

\
n

Newline

\
r

Carriage return

\
t

Horizontal tab

\
v

Vertical tab

3.1.1.2 Converting built
-
in types
转换内置类型

隐式转换和显式转换用在什么场合,有何
区别


Objects o
f one type can be converted into objects of another type either implicitly
(隐式
地)

or explicitly
(显式地)
. Implicit conversions happen automatically; the compiler takes
care of it for you. Explicit conversions happen when you "cast" a value to a different type.
T
he semantics
(语义)

of an explicit conversion are "Hey! Compiler! I know what I'm
doing." This is sometimes called "hitting it with the big hammer" and can be very useful
or very painful, depending on whether your thumb is in the way of the nail.

Implicit con
versions happen automatically and are guaranteed not to lose information.
For example, you can implicitly cast from a
short

int

(2 bytes) to an
int

(4 bytes). No
matter what value is in the
short
, it is not lost when converting to an
int
:

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


28

short x = 5;

int
y = x; // implicit conversion

If you convert the other way, however, you certainly can lose information. If the value in
the
int

is greater than 32,767, it will be truncated in the conversion. The compiler will not
perform an implicit conversion from
int

t
o
short
:

short x;

int y = 500;

x = y; // won't compile

You must explicitly convert using the cast operator:

short x;

int y = 500;

x = (short) y; // OK

All the intrinsic types define their own conversion rules. At times it is convenient to define
conversi
on rules for your user
-
defined types, as discussed in
Chapter 5
.

3.2. Variables and Constants
变量和常量

A
variable

is a storage location with a type. In the preceding examples, both
x

and
y

are
variables. Variables can have values assigned to them, and those values can be changed
programmatically.

(什么是变量?)

WriteLine()

写方法

The .NET Framework provides a
useful met hod for writ ing out put t o t he screen. The
det ails of t his met hod,
System.Console.WriteLine( )

, will become clearer as we
progress through the book, but the fundamentals are straightforward. Call the method as
shown in
Example 3
-
1
, passing in a s
tring that you want printed to the console (the
command prompt or shell window) and, optionally, parameters that will be substituted.
In the following example:

System.Console.WriteLine("After assignment, myInt: {0}", myInt);

the string "
After assignment, m
yInt:
" is printed as is, followed by the value in the
variable
myInt
. The location of the substitution parameter
{0}

specifies where the value
of the first output variable,
myInt
, is displayedin this case, at the end of the string. You'll
see a great deal
more about
WriteLine( )

in coming chapters.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


29

Create a variable by declaring its type and then giving it a name. You can initialize the
variable when you declare it, and you can assign a new value to that variable at any time,
changing the value held in the
variable. This is illustrated in
Example 3
-
1
.

Example 3
-
1. Initializing and assigning a value to a variable

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion

namespace InitializingVariables

{


class
Values


{


static void Main( )


{


int myInt = 7;


System.Console.WriteLine("Initialized, myInt: {0}", myInt);


myInt = 5;


System.Console.WriteLine("After assignment, myInt: {0}",


myInt);



}


}

}


Output:

Initialized, myInt: 7

After assignment, myInt: 5

Visual Studio 2005 creates a namespace and
using

directive (as well as a using
region) for every program. To save space, these are left out of most of the code
examples, though they are show
n in the example code you can download from
O'Reilly or LibertyAssociates.com.

Here we initialize the variable
myInt

to the value
7
, display that value, reassign the
variable with the value
5
, and display it again.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


30

3.2.1. Definite Assignment
明确赋值

C# requires definite assignment: that is, variables must be initialized or assigned to
before they are used. To test this rule, change the line that initializes
myInt

in

Example
3
-
1

to:

int myInt;

and save the revised program shown in
Example 3
-
2
.

Exa
mple 3
-
2. Using an uninitialized variable

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion


namespace UninitializedVariable

{


class UninitializedVariable


{


static void Main(string[] args)


{


int myInt;


System.
Console
.WriteLine


("Uninitialized, myInt: {0}", myInt);


myInt = 5;


System.
Console
.WriteLine("Assigned, myInt: {0}", myInt);



}


}

}


When you try to compile this listing, the C#

compiler will display an error message as
shown in
Figure 3
-
1
.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


31

Figure 3
-
1. Error message resulting from using an unassigned variable


Double
-
clicking the error message will bring you to the problem in the code.

It isn't legal to use an uninitialized vari
able in C#. So, does this mean you must initialize
every variable in a program? In fact, no. You don't actually need to initialize a variable,
but you must assign a value to it before you attempt to use it.
Example 3
-
3

illustrates a
correct program.

Examp
le 3
-
3. Assigning without initializing

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion


namespace AssigningWithoutInitializing

{


class AssigningWithoutInitializing


{


static void Main(stri
ng[] args)


{


int myInt;


myInt = 7;


System.Console.WriteLine("Assigned, myInt: {0}", myInt);


myInt = 5;


System.Console.WriteLine("Reassigned, myInt: {0}", myInt);


}


}

}


3.2.2. Constants
常量

什么是常量和变量有何区别?何时会用到常量?

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


32

A
constant

is a variable whose value can't be changed. Variables are a powerful tool, but
there are times when you want to manipulate a defined value, one whose value you want
to ensure remains constant. For example, you might need

to work with the

Fahrenheit
freezing and boiling points of water in a program simulating a chemistry experiment. Your
program will be clearer if you name the variables that store the values
FreezingPoint

and
BoilingPoint
, but you don't want to permit thei
r values to be reassigned. How do
you prevent reassignment? The answer is to use a constant.

Constants come in three flavors:
literals

,
symbolic

constants
, and
enumerations
. In this
assignment:

x = 32;

the value
32

is a literal constant. The value of
32

i
s always 32. You can't assign a new
value to
32
; you can't make
32

represent the value
99

no matter how you might try.

Symbolic constants assign a name to a constant value. You declare a symbolic constant
using the
const

keyword and the following syntax:

c
onst
type

identifier

=
value
;

A constant must be initialized when it is declared, and once initialized it can't be altered.

注意:常量在声明时必须被初始化,而且一旦初始化不能再更改。

For example:

const int FreezingPoint = 32;

In this declaration,
32

is a literal constant and
FreezingPoint

is a symbolic constant of
type
int
.
Example 3
-
4

illustrates the use of symbolic constants.

Example 3
-
4. Using symbolic
constants

#region Using directives

using System;

using System.Collections.Generic;

using System.Text;

#endregion


namespace SymbolicConstants

{


class SymbolicConstants


{

static void Main(string[] args)

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


33


{


const int FreezingPoint = 32;

// degrees Fahrenheit


const int BoilingPoint = 212;



System.Console.WriteLine("Freezing point of water: {0}",


FreezingPoint);


System.Console.WriteLine("Boiling point of water: {0}",


BoilingPoint);



//

BoilingPoint = 21;



}


}

}

Example 3
-
4

creates two symbolic integer constants:
FreezingPoint

and
BoilingPoint
.
As a matter of style, constant names are written in Pascal notation, but this is certainly
not required by the language.

These co
nstants serve the same purpose as always using the
literal

values
32

and
212

for
the freezing and boiling points of water in expressions that require them, but because
these constants have names, they convey far more meaning. Also, if you decide to switch
this program to Celsius, you can reinitialize these constants at compile time, to
0

and
100
,
respectively; all the rest of the code ought to continue to work.

To prove to yourself that the constant can't be reassigned, try uncommenting the last line
of the

program (shown in bold). When you recompile, you should receive the error shown
in
Figure 3
-
2
.

Figure 3
-
2. Warning that occurs when you try to reassign a
constant


3.2.3. Enumerations
枚举

什么是枚举?有何作用?
怎么用?

Enumerations

provide a powerful alternative to constants. An enumeration is a distinct
value type, consisting of a set of named constants (called the
enumeratorlist
).
一组常量的
集合。

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


34

In
Example 3
-
4
, you created two related constants:

const int F
reezingPoint = 32;

const int BoilingPoint = 212;

You might wish to add a number of other useful constants to this list, such as:

const int LightJacketWeather = 60;

const int SwimmingWeather = 72;

const int WickedCold = 0;

This process is somewhat cumbers
ome, and there is no logical connection between these
various constants. C# provides the
enumeration

to solve these problems:

enum Temperatures

{


WickedCold = 0,


FreezingPoint = 32,


LightJacketWeather = 60,


SwimmingWeather = 72,


BoilingPoint

= 212,

}

Every enumeration has an underlying type, which can be any integral type (
integer
,
short
,
long
, etc.) except for
char
. The technical definition of an enumeration is:

[
attributes
] [
modifiers
]
enum

identifier

[:
base
-
type
]
{
enumerator
-
list
};

The opt
ional attributes and modifiers are considered later in this book. For now, let's
focus on the rest of this declaration. An enumeration begins with the keyword
enum
, which
is generally followed by an identifier, such as:

enum Temperatures

The base type is

the underlying type for the enumeration. If you leave out this optional
value (and often you will), it defaults to
int
,

(枚举缺省类型为
int


but you are free to use
any of

the integral types (e.g.,
ushort
,
long
) except for
char
. For example, the following
fragmen
t declares an enumeration of unsigned integers (
uint
):

enum ServingSizes :uint

{


Small = 1,


Regular = 2,


Large = 3

}

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


35

Notice that an
enum

declaration ends with the enumerator list. The enumerator list
contains the constant assignments for the e
numeration, each separated by a comma.

Example 3
-
5

rewrites
Example 3
-
4

to use an enumeration.

Example 3
-
5. Using enumerations to simplify your code

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion


n
amespace EnumeratedConstants

{


class EnumeratedConstants


{



enum Temperatures


{


WickedCold = 0,


FreezingPoint = 32,


LightJacketWeather = 60,


SwimmingWeather = 72,


BoilingPoint = 212,


}




static void Main(string[] args)


{


System.Console.WriteLine("Freezing point of water: {0}",


(int)Temperatures.FreezingPoint);


System.Console.WriteLine("Boiling point of water: {0}",


(int)Temperatures.Boili
ngPoint);


}


}

}

As you can see, an
enum

must be qualified by its enumtype (e.g.,
Temperatures.WickedCold
). By default, an enumeration value is displayed using its
symbolic name (such as
BoilingPoint

or
FreezingPoint
). When you want to display the
value of an enumerated constant, you must cast the constant to its underlying type (
int
).
The integer value is passed to
WriteLine
, and that value is displayed.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


36

Each constant in an enumeration corresponds to a numerical valuein this case, an integer.
If yo
u don't specifically set it otherwise, the enumeration begins at 0 and each
subsequent value counts up from the previous.

If you create the following enumeration:

enum SomeValues

{


First,


Second,


Third = 20,


Fourth

}

the value of
First

will be
0
,
Second

will be
1
,
Third

will be
20
, and
Fourth

will be
21
.

Enums are formal types; therefore an explicit conversion is required to convert between
an enum type and an integral type.

3.2.4. Strings
字符串

It is nearly impossible to write a C# program without creating strings. A string

object
holds a string of characters.

You declare a string variable using the
string

keyword much as you would create an
instance of any object:

string myString;

A string l
iteral is created by placing double quotes around a string of letters:

"Hello World"

It is common to initialize a string variable with a string literal:

string myString = "Hello World";

Strings are covered in much greater detail in
Chapter 10
.

3.2.5. Ident
ifiers
标示符

Identifiers are names programmers choose for their types, methods, variables, constants,
objects, and so forth. An identifier must begin with a letter or an underscore
下划线
.

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


37

The Microsoft naming conventions suggest using camel notation (initial lowercase

such as
someName
) for variable names and Pascal notation (initial uppercase such as
SomeOtherName
) for method names and most other identifiers.

微软命名规则建议用
camel
规则命名变量名而
Pascal
规则命名方法
或其它
标示





Identifiers are case
-
sensitive, so C# treats
myVariable

and
MyVari
able

as two different
variable names.

3.3. Expressions
表达式

St at ement s t hat evaluat e t o a value are called
expressi ons
.
(什么是表达式)

You may be
surprised how many st at ement s do evaluat e t o a value. For example, an assi gnment such
as:

myVariable = 57;

is an expres
sion; it evaluates to the value assigned, which, in this case, is
57
.

Note that the preceding statement assigns the value
57

to the variable
myVariable
. The
assignment operator (
=
) doesn't test equality; rather it causes whatever is on the right
side (
57
)
to be assigned to whatever is on the left side (
myVariable
). All the C# operators
(including assignment and equality) are discussed later in this chapter (see "Operators").

Because
myVariable

=

57

is an expression that evaluates to
57
, it can be used as pa
rt of
another assignment operator, such as:

mySecondVariable = myVariable = 57;

What happens in this statement is that the literal value
57

is assigned to the variable
myVariable
. The value of that assignment (
57
) is then assigned to the second variable,
m
ySecondVariable
. Thus, the value
57

is assigned to both variables. You can therefore
initialize any number of variables to the same value with one statement:

a = b = c = d = e = 20;

3.4. Whitespace
空白

In t he C# language, spaces, t abs, and newlines are considered t o be "whit espace" (so
named because you see only t he whit e of t he underlying "page"). Ext ra whit espace is
generally ignored in C# st at ement s.
(多余的空白一般在语句中被忽略)

You can write:

myVariable = 5;

or:

myVariable


= 5;

Chapter3.C# Language Fundamentals
第三章

C#
语言基础


38

and the compiler will treat the two statements as identical.

The exception to this rule is that whitespace within strings isn't ignored. If you write:

Console.WriteLine("Hello World")

each space between "Hello" and "World" is
treated as another character in the string.

Most of the time the use of whitespace is intuitive. The key is to use whitespace to make
the program more readable to the programmer; the compiler is indifferent.

但有时候,
空白也不总是可以忽略的


However, there are instances in which the use of whitespace is quite significant. Although
the expression:

int x = 5;

is the same as:

int x=5;

it is not the same as:

intx=5;

The compiler knows that the whitespace on either side of the ass
ignment operator is
extra, but the whitespace between the type declaration
int

and the variable name
x

is
not

extra, and is required. This is not surprising: the whitespace allows the compiler to
parse the keyword
int

rather than some unknown term
intx
. Yo
u are free to add as
much or as little whitespace between
int

and
x

as you care to, but there must be at least
one whitespace character (typically a space or tab).

3.5. Statements
语句

In C# a complet e program inst ruct ion is called a
st at ement
. Programs consist of
sequences of C# st at ement s. Each st at ement must end wit h a semicolon (
;
). For
example:

int x; // a statement

x = 23; // another statement

int y = x; // yet another st
atement

C# statements are evaluated in order. The compiler starts at the beginning of a
statement list and makes its way to the bottom. This would be entirely straightforward,
Chapter3.C# Language Fundamentals
第三章

C#
语言基础


39

and terribly limiting, were it not for branching. There are two types of branche
s in a C#
program:
unconditional

branching

and
conditional

branching
.

Program flow is also affected by looping and iteration statements, which are signaled by
the keywords
for

,
while
,
do
,
in
, and
foreach
. Iteration is discussed later in this chapter.
For
now, let's consider some of the more basic methods of conditional and unconditional
branching.

3.5.1. Unconditional Branching Statements
无条件分支语句

无条件分支语句可以以两种方式中的任意一种创立:调用一个方法是第一种;

An unconditional branch is created in one of two ways. The first way is by in
voking a
method. When the compiler encounters the name of a method, it stops execution in the
current method and branches to the newly "called" method. When that method returns a
value, execution picks up in the original method on the line just below the m
ethod call.
Example 3
-
6

illustrates.

Example 3
-
6. Calling a method

#region Using directives

using System;

using System.Collections.Generic;

using System.Text;

#endregion


namespace CallingAMethod

{


class CallingAMethod


{


static void Main( )



{


Console.WriteLine("In Main! Calling SomeMethod( )...");


SomeMethod( );