1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft Visual C# 2005: Passo a Passo ppt

621 452 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Microsoft Visual C# 2005: Passo a Passo
Tác giả John Sharp
Trường học University of the State of São Paulo (UNESP)
Chuyên ngành Computer Science
Thể loại sổ tay hướng dẫn
Năm xuất bản 2006
Thành phố São Paulo
Định dạng
Số trang 621
Dung lượng 12,97 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Crie uma aplicação de console no Visual Studio 2005 No Microsoft Windows, clique no botão Iniciar, aponte para Todos os Programas, e então aponte para Microsoft Visual Studio 2005.. Voc

Trang 1

Visual C# 2005

Passo à Passo

de John Sharp

Trang 2

ễndice

INTRODUđấO 11

PARTE I Ố INTRODUđấO AO VISUAL C# E AO VISUAL STUDIO 2005 12

CAPễTULO 1 Ố BEM VINDO AO C# 13

COMEđANDO A PROGRAMAR COM O AMBIENTE VISUAL STUDIO 2005 14

Crie uma aplicação de console no Visual Studio 2005 14

ESCREVENDO SEU PRIMEIRO PROGRAMA 18

Escreva o código usando a tecnologia do IntelliSense 19

Construa e rode uma aplicação console 22

USANDO NAMESPACES 25

Tente nomes comuns 26

CRIANDO UMA APLICAđấO WINDOWS 28

Crie um Projeto Windows no Visual Studio 2005 28

Crie a interface do usuário 29

Escreva o código para o botão OK 36

Rode o programa Windows 36

CAPễTULO 1RÁPIDA REFERÊNCIA 37

CAPễTULO 2 - TRABALHANDO COM VARIÁVEIS, OPERADORES E EXPRESSỏES 39

ENTENDENDO AS DECLARAđỏES 39

USANDO IDENTIFICADORES 40

IDENTIFICANDO AS PALAVRAS CHAVES 41

USANDO VARIÁVEIS 41

Nomeando as Variáveis 42

Declarando Variáveis 43

TRABALHANDO COM TIPOS DE DADOS PRIMITIVOS 43

Não Assinalando Variáveis Locais 44

Mostrando Valores de Tipos de Dados Primitivos 44

Use os tipos de dados primitivos em código 46

USANDO OPERADORES ARITMÉTICOS 49

Determinando os Valores de um Operador 50

Examinando os Operadores Aritméticos 51

O trabalho com operadores aritméticos 51

Examine o código do programa MathsOperators 52

A propriedade Text e o método ToString 54

Controlando a Precedência 55

Usando a Associatividade para Avaliar as Expressões 56

INCREMENTANDO E DECREMENTANDO VARIÁVEIS 56

Prefixo e Pós-fixo 57

CAPễTULO 2RÁPIDA REFERÊNCIA 58

CAPễTULO 3 - ESCREVENDO MÉTODOS E APLICANDO ESCOPO 60

DECLARANDO MÉTODOS 60

Especificando a Sintaxe da Declaração do Método 61

Escrevendo as Declarações return 62

Examine as definições dos métodos 63

CHAMANDO MÉTODOS 65

Especificando a Sintaxe da Chamada de Método 65

Examine a chamada à método 66

APLICANDO O ESCOPO 67

Definindo um Escopo Local 68

Definindo o Escopo da Classe 69

Sobrecarregando Métodos 69

ESCREVENDO MÉTODOS 71

Desenvolva a lógica da aplicação 71

Escreva os métodos usando o Generate Method Stub Wizard 72

Refatoração de Código 75

Teste o programa 75

Pise dentro dos métodos usando o Depurador do Visual Studio 2005 76

Trang 3

CAPễTULO 3-RÁPIDA REFERÊNCIA 79

CHAPTER 4 - USING DECISION STATEMENTS 81

DECLARING BOOL VARIABLES 81

USING BOOLEAN OPERATORS 82

Understanding Equality and Relational Operators 82

Understanding Conditional Logical Operators 83

Summarizing Operator Precedence and Associativity 84

USING IF STATEMENTS TO MAKE DECISIONS 85

Understanding if Statement Syntax 85

Using Blocks to Group Statements 86

Cascading if Statements 87

Write if statements 87

USING SWITCH STATEMENTS 91

Understanding switch Statement Syntax 91

Following the switch Statement Rules 92

Write switch statements 93

CHAPTER 4QUICK REFERENCE 95

CHAPTER 5 - USING COMPOUND ASSIGNMENT AND ITERATION STATEMENTS 97

USING COMPOUND ASSIGNMENT OPERATORS 97

WRITING WHILE STATEMENTS 98

Write a while statement 99

WRITING FOR STATEMENTS 103

Understanding for Statement Scope 104

WRITING DO STATEMENTS 105

Write a do statement 106

Step through the do statement 109

CHAPTER 5QUICK REFERENCE 112

CAPễTULO 6 - GERENCIANDO ERROS E EXCEđỏES 114

COPIANDO COM ERROS 115

TENTANDO CốDIGO E CAPTURA DE EXCEđỏES 116

Manipulando uma Exceção 117

Exceções Não Manipuladas 117

Usando Múltiplos Manipuladores catch 119

Pegandos Múltiplas Exceções 120

Escreva uma declaração try/catch 121

USANDO CÁLCULO CHECKED E UNCHECKED DE INTEIRO 125

Escrevendo Declarações checked 126

Escrevendo Expressões checked 127

Use as expressões checked 128

LANđANDO EXCEđỏES 129

Lance sua própria exceção 131

Capture sua própria exceção 133

USANDO UM BLOCO FINALLY 135

CAPễTULO 6-RÁPIDA REFERÊNCIA 137

PARTE II - ENTENDENDO A LINGUAGEM C# 139

CAPễTULO 7 - CRIANDO E GERENCIANDO CLASSES E OBJETOS 140

ENTEDENDO A CLASSIFICAđấO 141

OPROPốSITO DO ENCAPSULAMENTO 141

DEFININDO E USANDO UMA CLASSE 142

CONTROLANDO A ACESSIBILIDADE 143

TRABALHANDO COM CONSTRUTORES 145

Sobrecarregando Construtores 146

Classes Parciais 147

Escreva construtores e crie objetos 148

Escreva e chame métodos de instância 153

ENTENDENDO OS MÉTODOS E DADOS ESTÁTICOS 155

Trang 4

Criando um Campo Compartilhado 156

Criando um Campo static com a Palavra Chave const 157

Classes Estáticas 157

Escreva para os membros e chame os métodos estáticos 158

CAPễTULO 7-RÁPIDA REFERÊNCIA 161

CAPễTULO 8 Ố ENTENDENDO VALORES E REFERÊNCIAS 164

COPIANDO VARIÁVEIS INT E CLASSES 164

Use parâmetros de valor e parâmetros de referência 166

USANDO OS PARÂMETROS REF E OUT 170

Criando Parâmetros ref 171

Criando Parâmetros out 172

Use os parâmetros ref 173

COMO É ORGANIZADA A MEMốRIA DO COMPUTADOR 175

Usando a Stack e a Heap 176

ACLASSE SYSTEM.OBJECT 177

OBOXING 178

OUNBOXING 179

Os Ponteiros e o Código Inseguro 182

CAPễTULO 8-RÁPIDA REFERÊNCIA 184

CAPễTULO 9 - CRIANDO TIPOS VALOR COM ENUMERAđỏES E STRUCTS 186

TRABALHANDO COM ENUMERAđỏES 186

Declarando um tipo enumeração 187

Usando uma Enumeração 187

Escolhendo Valores Literais de Enumeração 188

Escolhendo um Tipo Subjacente da Enumeração 189

Crie e use um tipo enumeração 190

TRABALHANDO COM TIPOS ESTRUTURA 192

Declarando o Tipo Estrutura 194

Entendendo Estrutura e as Diferenças para a Classe 195

Declarando Variáveis de Estruturas 197

Entendendo a Inicialização da Estrutura 198

Copiando Variáveis de Estruturas 200

Crie e use um tipo struct 201

CAPễTULO 9-RÁPIDA REFERÊNCIA 204

CHAPTER 10 - USING ARRAYS AND COLLECTIONS 207

WHAT IS AN ARRAY? 207

Declaring Array Variables 207

Creating Array Instances 208

Initializing Array Variables 209

Accessing Individual Array Elements 210

Iterating Through an Array 210

Copying Arrays 211

WHAT ARE COLLECTION CLASSES? 213

The ArrayList Class 214

The Queue Class 216

The Stack Class 217

The Hashtable Class 218

The SortedList Class 219

Comparing Arrays and Collections 220

Using Collection Classes to Play Cards 220

Deal the cards 220

Shuffle the pack 221

Return the cards to the pack 224

CHAPTER 10QUICK REFERENCE 225

CAPễTULO 11 - ENTENDENDO ARRAYS DE PARÂMETROS 227

USING ARRAY ARGUMENTS 228

Declaring params Arrays 229

Using params object[ ] 232

Using params Arrays 233

Trang 5

Write a params array method 233

Test the Util.Sum method 235

CHAPTER 11QUICK REFERENCE 236

CAPễTULO 12 - TRABALHANDO COM A HERANđA 238

OQUE É A HERANđA? 239

USANDO A HERANđA 239

Classes Base e Classes Derivadas 239

Chamando a o Construtor da Classe Base 241

Assinalando Classes 243

new Métodos 244

Métodos Virtuais 245

Métodos Virtuais e o Polimorfismo 247

Os Métodos Sobrescritos 249

Acesso protected 250

CRIANDO INTERFACES 251

A Sintaxe da Interface 252

Restrições das Interfaces 252

Implementando uma Interface 253

Referenciando uma Classe Por Sua Interface 255

Trabalhando com Múltiplas Interfaces 256

CLASSES ABSTRATAS 256

CLASSES SELADAS 259

Métodos Selados 260

ESTENDENDO UMA HIERARQUIA DE HERANđA 260

Entenda a hierarquia da herança e seu propósito 261

Escreva a classe ColorSyntaxVisitor 264

SUMARIZANDO AS COMBINAđỏES DAS PALAVRTAS CHAVES 269

CAPễTULO 12-RÁPIDA REFERÊNCIA 270

CAPễTULO 13 Ố USANDO O GARBAGE COLLECTION E O GERENCIAMENTO DE RECURSOS 272

AVIDA E A DURAđấO DE UM OBJETO 272

Escrevendo Destrutores 274

Por que Usar o Garbage Collection? 275

Como o Garbage Collection Funciona? 277

Recomendações 278

ADMINISTRAđấO DE RECURSOS 278

O Método Disposal 278

Disposição de Exceção Segura 279

A Declaração using 280

Chamando o método Dispose de um Destrutor 282

TORNANDO O CốDIGO UMA EXCEđấO SEGURA 284

Escreva uma declaração using 284

CAPễTULO 13-RÁPIDA REFERÊNCIA 286

PARTE III - CRIANDO COMPONENTES 289

CAPễTULO 14 - IMPLEMENTANDO PROPRIEDADES PARA ACESSAR ATRIBUTOS 290

COMPARANDO OS CAMPOS E OS MÉTODOS 291

OQUE SấO PROPRIEDADES? 293

Usando as Propriedades 295

Propriedades de Somente Leitura 296

Propriedades de Somente Escrita 296

Acessibilidade da Propriedade 297

ENTENDENDO AS RESTRIđỏES DAS PROPRIEDADES 298

Usando Adequadamente as Propriedades 299

DECLARANDO PROPRIEDADES DE INTERFACE 300

Usando Propriedades em uma Aplicação Windows 301

O Uso das propriedades 302

CAPễTULO 14-RÁPIDA REFERÊNCIA 306

CAPễTULO 15 - USANDO INDEXADORES 308

Trang 6

OQUE É UM INDEXADOR? 308

Um Exemplo Que não Usa indexadores 308

Os operadores Bitwise e Shift 309

O Mesmo Exemplo Usando indexadores 310

Endentendo os Acessores Indexadores 313

Comparando Indexadore e Arrays 313

OS INDEXADORES NAS INTERFACES 316

USANDO INDEXADORES EM UMA WINDOWS APPLICATION 317

Familiarize-se com a aplicação 317

Escreva os indexadores 319

Chame os indexadores 321

Rode a aplicação 322

CAPễTULO 15-RÁPIDA REFERÊNCIA 323

CAPễTULO 16 - DELEGADOS E EVENTOS 326

DECLARANDO E USANDO OS DELEGADOS 327

OCENÁRIO DA FÁBRICA DE AUTOMAđấO 327

Implementando a Fábrica sem o Uso de Delegados 328

Implementando a Fábrica pelo Usi de um Delegado 328

USANDO DELEGADOS 332

Termine a aplicação do relógio digital 332

OS MÉTODOS ANÔNIMOS E OS DELEGADOS 335

Criando um Adaptador de Método 335

Usando um Método Anônimo como um Adaptador 336

Caracterắsticas dos Métodos Anônimos 337

PERMITINDO NOTIFICAđỏES COM EVENTOS 337

DECLARANDO UM EVENTO 338

SUBSCREVENDO A UM EVENTO 339

TIRANDO A SUBSCRIđấO DE UM EVENTO 339

DISPARANDO UM EVENTO 340

ENTENDENDO OS EVENTOS DA GUI 340

USANDO EVENTOS 342

Refaça a aplicação do relógio digital 343

CAPễTULO 16-RÁPIDA REFERÊNCIA 346

CAPễTULO 17 Ố INTRODUZINDO OS GENÉRICOS 349

OPROBLEMA COM OS OBJECTS 349

ASOLUđấO GENÉRICA 351

Genéricos vs Classes Generalizadas 354

Os Genéricos e as Restrições 355

CRIAđấO DE UMA CLASSE GENÉRICA 355

A Teoria da Árvore Binária 355

Construindo uma Classe Tree Binária que Usa Genéricos 359

Crie a classe Tree<T> 362

Teste a classe Tree<T> 366

CRIANDO UM MÉTODO GENÉRICO 369

Definindo um Método Genérico para Construir uma árvore Binária 370

Escreva o método BuildTree 370

Teste o método BuildTree 372

CAPễTULO 17-RÁPIDA REFERÊNCIA 372

CAPễTULO 18 - ENUMERANDO COLEđỏES 374

ENUMERANDO OS ELEMENTOS NA COLEđấO 374

Implementando um Enumerador Manualmente 376

Crie a classe TreeEnumerator 376

Implementando a Interface IEnumerable 381

Implemente a interface IEnumerable<T> na classe Tree<T> 381

Teste o enumerador 382

IMPLEMENTANDO UM ENUMERADOR USANDO UM ITERATOR 383

Um Simples Iterator 383

Definindo um Enumerador para a Class Tree<T> Usando um Iterator 385

Adicione um enumerador à classe Tree<T> 386

Teste o novo enumerador 387

Trang 7

CAPễTULO 18-RÁPIUDA REFERÊNCIA 388

CAPễTULO 19 Ố SOBRECARGA DE OPERADORES 390

ENTENDENDO OS OPERADORES 390

Limitações dos Operadores 391

Sobrecarga de Operadores 392

Criando Operadores Simétricos 394

Os operadores e a Common Language Specification 396

ENTENDENDO A ASSINALAđấO DE COMBINAđấO 396

DECLARANDO OPERADORES DE INCREMENTO E DECREMENTO 397

Operadores em Structs e Classes 398

DEFININDO PARES DE OPERADORES 399

IMPLEMENTANDO UM OPERADOR 400

Escreva as sobrecargas do operator+ 401

ENTENDENDO OS OPERADORES DE CONVERSấO 403

Fornecendo Conversões Embutidas 404

Implementando Operadores de Conversão definidos pelo usuário 405

Criando Operadores Simétricos Revisados 406

Adicionando um Operador de Conversão Implắcito 407

Escreva o operador de conversão 407

CAPễTULO 19-RÁPIDA REFERÊNCIA 409

PARTE IV - EXPLORANDO AS APLICAđỏES WINDOWS 411

CAPễTULO 20 - INTRODUZINDO O WINDOWS FORMS 412

CRIANDO SUA APLICAđấO 413

Criando uma Aplicação Windows Forms 413

Crie o projeto Middleshire Bell Ringers Association 414

Configure as propriedades do form 414

Como se Executa uma Aplicação Windows Forms 417

O que são as Propriedades Comuns do Windows Forms? 418

Alterando as Propriedades Programaticamente 420

ADICIONANDO OS CONTROLES AO FORM 421

Usando os Controles do Windows Forms 422

Adicionando os controles do Windows Forms 423

Configuração das Propriedades do Controle 424

Mudando as Propriedades Dinamicamente 429

Crie o método Reset 430

Programando a Interface do Usuário 432

PUBLICANDO EVENTS NO WINDOWS FORMS 434

Processando Events no Windows Forms 434

Manipule o evento Click para o botão Clear 435

Manipule o evento Click do botão Add 436

Controle o evento Final para o form 437

RODE A APLICAđấO 438

CAPễTULO 20-RÁPIDA REFERÊNCIA 439

CAPễTULO 21 - TRABALHANDO COM MENÚS E DIALOG BOXES 441

DIRETRIZES E ESTILO DO MENÚ 442

ADICIONANDO MENÚS E PROCESSANDO EVENTOS DO MENÚ 442

Criando um Menú 443

Crie o menú File 443

Os Tipos de ễtens do Menu Strip 446

Configurando as Propriedades dos ắtens do Menú 446

Configure as propriedades dos ắtens de menú 446

Teste o menú 449

Outras Propriedades de ễtens de Menú 449

Eventos de Menú 450

Manipule os eventos dos ắtens do menú 451

Teste os eventos de menú 452

OS MENÚS POP-UP 453

Criando Menús Pop-Up 453

Trang 8

Crie os menus pop-up firstName e lastName 453

Escreva o método de evento saveMemberClick 457

Crie o menu de contexto MemberForm 458

USANDO OS CONTROLES COMUNS DE DIÁLOGO 460

Usando o Controle SaveFileDialog 461

Use um controle SaveFileDialog 461

Usando uma Impressora 463

Use um controle PrintDialog 464

Use um controle PrintDocument 464

CAPễTULO 21-RÁPIDA REFERÊNCIA 467

CAPễTULO 22 Ố EXECUTANDO A VALIDAđấO 470

VALIDANDO DADOS 470

A Propriedade CausesValidation 471

Validação de Eventos 471

UM EXEMPLO -MANUTENđấO PERSONALIZADA 471

Uma Primeira Tentativa para Executar a Validação 472

Examine o programa 472

Rode a aplicação 475

Sendo Discreto 476

Mude o ponto onde os dados são validados 476

Teste a aplicação novamente 478

Usando um Controle ErrorProvider 478

Adicione um controle ErrorProvider 478

Teste o controle ErrorProvider 481

Adicionando uma Status Bar 482

Adicione um controle StatusStrip 482

Teste a status bar 484

CHAPTER 22QUICK REFERENCE 485

PART V - MANAGING DATA 486

CHAPTER 23 - USING A DATABASE 487

USING ADO.NETDATABASES 487

The Northwind Traders Database 488

Creating the Database 488

Create the database 488

Accessing the Database 489

Create a data source 489

Browse product and supplier information 496

Display product data in the Windows Forms application 497

USING ADO.NETPROGRAMMATICALLY 501

Connect to the database 502

Query the Orders table 503

Fetch data and display orders 504

Disconnect from the database 506

Handle null database values 507

CHAPTER 23QUICK REFERENCE 508

CHAPTER 24 - WORKING WITH DATA BINDING AND DATASETS 510

WINDOWS FORMS CONTROLS AND DATA BINDING 510

Defining a DataSet and Using Simple Data Binding 511

Defining a DataSet class 511

Bind to a column in a DataTable 516

Using Complex Data Binding 518

Create and configure the data source 518

Bind a ComboBox to the DataTable 519

UPDATING A DATABASE USING A DATASET 521

Managing Connections 521

Handling Multi-User Updates 522

Using a DataSet with a DataGridView Control 523

Add the DataGridView control to the form 523

Create a DataAdapter for fetching Products and bind it to the DataGridView control 523

Trang 9

Validating User Input in the DataGridView Control 526

Configure the DataGridView control to constrain user input 526

Handle the CellValidating, CellEndEdit, and DataError event 527

Performing Updates by Using a DataSet 529

Validate the changes and handle errors 530

Update the database 532

CHAPTER 24QUICK REFERENCE 533

PART VI - BUILDING WEB APPLICATIONS 536

CHAPTER 25 - INTRODUCING ASP.NET 537

UNDERSTANDING THE INTERNET AS AN INFRASTRUCTURE 537

Understanding Web Server Requests and Responses 538

Managing State 538

Understanding ASP.NET 539

CREATING WEB APPLICATIONS WITH ASP.NET 541

Building an ASP.NET Application 541

Create the Web application 541

Lay out the Web form 542

Test the Web form 551

Understanding Server Controls 553

Examine a Server control 553

Write event handlers 554

Test the Web form again 557

Creating and Using a Theme 560

Create a new theme 561

Create a Web configuration file and apply the theme 562

CHAPTER 25QUICK REFERENCE 563

CHAPTER 26 UNDERSTANDING WEB FORMS VALIDATION CONTROLS 565

COMPARING SERVER AND CLIENT VALIDATIONS 565

Server Validation 565

Client Validation 566

Implementing Client Validation 567

Add RequiredFieldValidator controls 567

Add a RangeValidator control 569

Add a ValidationSummary control 570

CHAPTER 26QUICK REFERENCE 573

CHAPTER 27 SECURING A WEB SITE AND ACCESSING DATA WITH WEB FORMS 574

Using the Web Forms GridView Control 574

MANAGING SECURITY 575

Understanding Forms-Based Security 575

Implementing Forms-Based Security 576

Create the Northwind Web Site 576

Build the login form 576

Configure Website Security and enable Forms-based security 578

QUERYING DATA 582

Displaying Customer Information 582

Create a connection to the Northwind Database 582

Lay out the CustomerData Web form 584

Test the CustomerData form 585

Displaying Data in Pages 586

Modify the GridView to use paging 586

Optimizing Data Access 587

Caching Data in a Data Source 588

Investigate caching with a SqlDataSource object 589

EDITING DATA 590

Deleting Rows from a GridView Control 590

Create the Delete button 591

Updating Rows in a GridView Control 592

Create the Edit, Update, and Cancel buttons 592

CHAPTER 27QUICK REFERENCE 593

Trang 10

CHAPTER 28 - CREATING AND USING A WEB SERVICE 595

WHAT IS A WEB SERVICE? 595

The Role of SOAP 596

What Is the Web Services Description Language? 598

BUILDING THE PRODUCTSERVICE WEB SERVICE 600

Creating the ProductService Web Service 600

Create the Web service 600

Grant Access Rights to use the Windows Event Log 605

Test the Web method 605

5 Close both Internet Explorer windows and return to the Visual Studio 2005 programming environment Handling Complex Data 607

Define the Product class 608

Create the GetProductInfo Web method 610

WEB SERVICES,CLIENTS, AND PROXIES 613

Talking SOAP: The Difficult Way 613

Talking SOAP: The Easy Way 614

Consuming the ProductService Web Service 614

Create a Web service client application 614

Add a reference to the Web service 615

Execute a Web method 616

Test the application 617

CHAPTER 28QUICK REFERENCE 620

Trang 11

Introdução

O Microsoft Visual C# é uma poderosa mas simples linguagem apontada principalmente para os programadores que criam aplicações usando o Microsoft .NET Framework Ela herda muitas das melhores características do C++ e do Microsoft Visual Basic, mas pouco das inconsistências e anacronismos, resultando

em uma linguagem limpa e mais lógica Com o advento do C# 2.0 viu-se várias novas características importantes acrescentadas à linguagem, inclusive os Generics, os Iteratores e métodos anônimos O ambiente de desenvolvimento fornecido por Microsoft que Visual Studio 2005 faz destas poderosas características fáceis de se usar, e os muitos novos assistentes e melhoramentos incluídos do Visual Studio 2005 podem melhorar muito sua produtividade como um programador Microsoft Visual C# is a powerful but simple language aimed primarily at developers creating applications by using the Microsoft NET Framework It inherits many of the best features of C++ and Microsoft Visual Basic, but few of the inconsistencies and anachronisms, resulting in a cleaner and more logical language The advent

of C# 2.0 has seen several important new features added to the language, including Generics, Iterators, and anonymous methods The development environment provided by Microsoft Visual Studio 2005 makes these powerful features easy to use, and the many new wizards and enhancements included in Visual Studio 2005 can greatly improve your productivity as a developer.

O objetivo principal deste livro é lhe ensinar os fundamentos de se programar com

o C# usando o Visual Studio 2005 e o NET Framework Você aprenderá as características da linguagem C# e então as usará para construir aplicações que rodam no sistema operacional Windows da Microsoft Assim que você completar este livro, você terá um completo entendimento do C# e o terá usado para construir aplicações do Windows Forms, para acessar o banco de dados Microsoft SQL Server, para desenvolver aplicações da Web no ASP.NET e para construír e consumir um serviço de Web The aim of this book is to teach you the fundamentals of programming with C# by using Visual Studio 2005 and the NET Framework You will learn the features of the C# language, and then use them to build applications running on the Microsoft Windows operating system By the time you complete this book, you will have a thorough understanding of C# and will have used it to build Windows Forms applications, access Microsoft SQL Server databases, develop ASP.NET Web applications, and build and consume a Web service.

Trang 12

Parte I – Introdução ao Visual C# e ao Visual

Studio 2005

Trang 13

Capítulo 1 – Bem Vindo ao

• Criar uma aplicação de console do C# Create a C# console application.

• Usar os namespaces Use namespaces.

• Criar uma aplicação Windows Forms C# Create a C# Windows Forms application.

O Visual C# é uma poderosa linguagem orientada à componente da Microsoft Ele desempenha um importante papel na arquitetura do NET Framework, e algumas pessoas fizeram comparações com o papel que o C teve no desenvolvimento do UNIX Se você já souber uma linguagem como o C, o C++, ou Java, você achará a sintaxe do C# muito familiar porque ele usa os mesmos parênteses para delimitar

os blocos de código Porém, se você está acostumado a programar em outras linguagens, você deve poder acompanhar logo a sintaxe e o sentido do C# ; você apenas precisa aprender colocar os parênteses e os pontos e vírgulas no lugar certo Esperançosamente este é apenas um livro para o ajudar! Microsoft Visual C# is Microsoft's powerful, component-oriented language C# plays an important role in the architecture of the Microsoft NET Framework, and some people have drawn comparisons to the role that C played in the development of UNIX If you already know a language such as C, C++, or Java, you'll find the syntax of C# reassuringly familiar because it uses the same curly brackets to delimit blocks of code However, if you are used to programming in other languages, you should soon be able to pick up the syntax and feel of C#; you just need to learn to put the curly brackets and semi-colons in the right place Hopefully this is just the book to help you!

Nesta Parte I, você aprenderá os fundamentos do C# Você descobrirá como declarar variáveis e como usar os operadores de adição (+) e de subtração (-) para criar valores Você verá como escrever métodos e argumentos de passagem para métodos Você também aprenderá a usar as declarações de seleção como as

declarações de repetição, de if e while Finalmente, você entenderá como o C# usa

as exceções para controlar erros de uma maneira graciosa, fácil de usar Estes tópicos formam o núcleo do C# , e você progredirá, aos poucos, para os recursos mais avançadas na Parte II até a Parte VI In Part I, you'll learn the fundamentals of C# You'll discover how to declare variables and how to use operators such as plus (+) and minus (-) to create values You'll see how to write methods and pass arguments to methods You'll also learn how to use selection statements such as

if and iteration statements such as while Finally, you'll understand how C# uses exceptions to handle errors in a

graceful, easy-to-use manner These topics form the core of C#, and from this solid foundation, you'll progress to more advanced features in Part II through Part VI.

Trang 14

Começando a Programar com o Ambiente Visual Studio

2005

O Visual Studio 2005 é um ambiente de ferramentas de programação rico que contém toda a funcionalidade você precisará para criar grandes ou pequenos projetos em C# Você pode criar projetos até mesmo sem emendas que combinam módulos de diferentes linguagens No primeiro exercício, você começará o ambiente de programação do Visual Studio 2005 e aprenderá a criar uma aplicação

de console Visual Studio 2005 is a tool-rich programming environment containing all the functionality you'll need to create large or small C# projects You can even create projects that seamlessly combine modules from different languages In the first exercise, you'll start the Visual Studio 2005 programming environment and learn how

to create a console application.

Crie uma aplicação de console no Visual Studio 2005

No Microsoft Windows, clique no botão Iniciar, aponte para Todos os Programas, e então aponte para Microsoft Visual Studio 2005 In Microsoft Windows, click the Start button, point to All Programs, and then point to Microsoft Visual Studio 2005.

Clique no ícone Microsoft Visual Studio 2005 O Visual Studio 2005 iniciará Click the Microsoft Visual Studio 2005 icon Visual Studio 2005 starts

NOTA - Se esta é na primeira vez que você rodou o Visual Studio 2005, você

poderá ver um caixa de diálogo o incitando a escolher suas configurações do ambiente de desenvolvimento padrão O Visual Studio 2005 pode se adaptar

se adaptando à sua linguagem de desenvolvimento preferida As várias caixas

de diálogo e ferramentas do ambiente de desenvolvimento integrado (IDE) terá o seu conjunto de seleções padrão para a linguagem que você escolher

Selecione Visual C# Development Settings da lista, e então clique no botão

Start Visual Studio Depois de uma pequena demora, a IDE do Visual Studio

2005 aparecerá If this is the first time that you have run Visual Studio 2005, you might see a dialog

box prompting you to choose your default development environment settings Visual Studio 2005 can tailor itself according your preferred development language The various dialog boxes and tools in the integrated development environment (IDE) will have their default selections set for the language you choose Select Visual C# Development Settings from the list, and then click the Start Visual Studio button After a short delay, the Visual Studio 2005 IDE appears.

Trang 15

3 No menú File, aponte para New, e então clique em Project A dialog box New Project se abrirá Esta dialog box lhe permite criar um novo projeto usando vários modelos (templates), como Windows Application, Class Library e Console Application que especifica o tipo de aplicação que você queira criar On the File menu, point to New, and then click Project The New Project dialog box opens This dialog box allows you to create a new project using various templates, such as Windows Application, Class Library, and Console Application, that specify the type of application you want to create.

NOTA - Os modelos atuais disponíveis dependem da versão do Visual Studio

2005 que você está usando Também é possível definir novos modelos de projetos, mas isso está além da extensão deste livro The actual templates available depend on the version of Visual Studio 2005 you are using It is also possible to define new project templates, but that is beyond the scope of this book.

Trang 16

No painel Templates, clique no ícone Console Application In the Templates pane, click the Console Application icon

No campo Location, digite C:\Documents and Settings \ MeuNome \ Meus Documents\Microsoft Press\Visual CSharp Passo por Step\Chapter 1 In the Location

field, type C:\Documents and Settings\ YourName \My Documents\ Microsoft Press\Visual CSharp Step by

Step\Chapter 1.

Substitua o texto MeuNome neste caminho pelo nome do usuário do Windows Para economizar um pouco de espaço ao longo do resto deste livro, nós recorreremos simplesmente ao caminho "C:\Documents and Settings\MeuNome\My Documents" como seu diretório dos "\ Meus Documentos" Replace the text YourName in this path with your

Windows user name To save a bit of space throughout the rest of this book, we will simply refer to the path

“C:\Documents and Settings\YourName\My Documents” as your “\My Documents” folder.

NOTA Se a diretório que você especificou não existir, o Visual Studio 2005 o

criará para você If the folder you specify does not exist, Visual Studio 2005 creates it for you.

No campo Name, digite TextHello In the Name field, type TextHello

Assegure-se de que o Create Directory do check box do Solution foi marcado e então clique no OK O novo projeto abrirá Ensure that the Create Directory for Solution check box

is checked and then click OK The new project opens.

A barra do menú na parte superior da tela fornece acesso às características que você usará no ambiente de programação Você pode usar o teclado ou o mouse para acessar os menús e comandos exatamente como você faz em todos os programas baseados no Windows A toolbar fica situada em baixo da barra de menú e fornece atalhos de botão para rodar os comandos freqüentemente usados

A janela Code (Código) e a Text Editor (Editod de Texto) que ocupam a parte principal da IDE exibem os conteúdos dos arquivos fonte Em um projeto com

Trang 17

multi-arquivo, cada arquivo fonte tem sua própria aba etiquetada com o nome do arquivo fonte Você pode clicar na aba uma vez para trazer o arquivo fonte nomeado para o primeiro plano da janela do Código e do Editor de Texto O Solution Explorer exibe os nomes dos arquivos associados com o projeto, entre outros artigos Você também pode clicar duas vezes um nome de arquivo no Solution Explorer para trazer aquele arquivo fonte para o primeiro plano da janela

de Código e do Editor de Texto The menu bar at the top of the screen provides access to the features

you'll use in the programming environment You can use the keyboard or the mouse to access the menus and

commands exactly as you can in all Windows-based programs The toolbar is located beneath the menu bar and provides button shortcuts to run the most frequently used commands The Code and Text Editor window occupying the main part of the IDE displays the contents of source files In a multi-file project, each source file has its own tab

labeled with the name of the source file You can click the tab once to bring the named source file to the foreground

in the Code and Text Editor window The Solution Explorer displays the names of the files associated with the

project, among other items You can also double-click a file name in the Solution Explorer to bring that source file to the foreground in the Code and Text Editor window.

Antes de escrever o código, examine os arquivos listados no Solution Explorer que

o Visual Studio 2005 criou como parte de seu projeto: Before writing the code, examine the files listed in the Solution Explorer, which Visual Studio 2005 has created as part of your project:

Solution 'TextHello'

Este é o arquivo da solução de alto nível do qual existe um por aplicação Se você usa o Windows Explorer para ver o seu diretório \My Documents\Visual CSharp Passo por Step\Chapter 1\TextHello, você verá que o nome atual deste arquivo é TextHello.sln Cada arquivo de solução contém referências a um ou mais arquivos de projeto This is the top-level solution file, of which there is one per application If you use Windows Explorer to look at your \My Documents\Visual CSharp Step by Step\Chapter 1\TextHello folder, you'll see that the actual name of this file is TextHello.sln Each solution file contains references to one or more project files.

Trang 18

is the C# project file Each project file references one or more files containing the source code and other items for the project All the source code in a single project must be written in the same programming language In Windows Explorer, this file is actually called TextHello.csproj, and it is stored in your \My Documents\Visual CSharp Step by Step\Chapter 1\TextHello\TextHello folder.

Properties

Este é um diretório do projeto TextHello Se você ampliá-lo, você verá que ele contém um arquivo chamado AssemblyInfo.cs O AssemblyInfo.cs é um arquivo especial que você pode usar para acrescentar atributos a um programa, como o nome do autor, a data em que o programa foi escrito, e assim por diante Há atributos adicionais que você pode usar para modificar o modo no qual o programa rodará Estes atributos estão fora da extensão deste livro This is a folder in the TextHello project If you expand it, you will see that it contains a file called AssemblyInfo.cs

AssemblyInfo.cs is a special file that you can use to add attributes to a program, such as the name of the

author, the date the program was written, and so on There are additional attributes that you can use to modify the way in which the program will run These attributes are outside the scope of this book.

References

Este é um diretório que contém referências ao código compilado que sua aplicação pode usar Quando o código é compilado, ele é convertido em um assembly e determinado um nome sem igual Os programadores usam assemblies para empacotar pedaços úteis de código que eles escreveram para a distribuição a outros programadores que poderiam os querer os usar nas suas aplicações Muitas das características que você estará usando quando escrevendo aplicações usandom este livro farão uso de assemblies fornecidos pela Microsoft com o Visual Studio 2005 This is a folder that contains references to compiled

code that your application can use When code is compiled, it is converted into an assembly and given a unique

name Developers use assemblies to package up useful bits of code that they have written for distribution to other developers that might want to use them in their applications Many of the features that you will be using when writing applications using this book will make use of assemblies provided by Microsoft with Visual Studio

2005.

Program.cs

Este é um arquivo fonte do C#, e é aquele exibido na janela do Código e do Editor de Texto quando o projeto inicialmente é criado Você escreverá seu código neste arquivo Ele contém algum código que o Visual Studio 2005 fornece automaticamente, o qual você examinará brevemente This is a C# source file, and is the one displayed in the Code and Text Editor window when the project is first created You will write your code in this file It contains some code that Visual Studio 2005 provides automatically, which you will examine shortly.

Escrevendo Seu Primeiro Programa

O arquivo Program.cs define uma classe chamada Program que contém um método chamado Main Todos os métodos devem ser definidos dentro de uma classe O método Main é especial - ele designa o ponto de entrada do programa Ele deve ser

Trang 19

um método estático (Os métodos são discutidos no "Capítulo 3 - Escrevendo Métodos e Aplicando Extensão" Os métodos estáticos são discutidos no "Capítulo 7 Criando e Administrando Classes e Objetos" O método Main é discutido no

"Capítulo 11, Entendendo Arrays de Parâmetro") The Program.cs file defines a class called

Program that contains a method called Main All methods must be defined inside a class The Main method is

special—it designates the program's entry point It must be a static method (Methods are discussed in Chapter 3,

“Writing Methods and Applying Scope.” Static methods are discussed in Chapter 7, “Creating and Managing Classes

and Objects.” The Main method is discussed in Chapter 11, “Understanding Parameter Arrays.”)

IMPORTANTE O C# é uma linguagem caso-sensível Você tem que digitar

Main com um M maiúsculo C# is a case-sensitive language You must spell Main with a capital

M.

Nos exercícios seguintes, você escreverá o código para exibir a mensagem Hello World no console; você construirá e rodará sua aplicação de console Hello World; você aprenderá como são usados os namespaces para dividir os elementos do código In the following exercises, you'll write the code to display the message Hello World in the console; you'll

build and run your Hello World console application; you'll learn how namespaces are used to partition code elements.

Escreva o código usando a tecnologia do IntelliSense

1 No Na janela do Editor de Texto e de Código que exibe o arquivo Program.cs, coloque o cursor no método Main depois da chave de abertura e digite Console Assim que você digitar a letra C no começo da palavra Console, uma lista do IntelliSense aparecerá Esta lista contém todas as palavras chaves e tipos de dados

do C# que são válidos neste contexto Você, ou pode continuar a digitação, ou enrolar pela lista e clicar duas vezes no ítem de console com o mouse Alternativamente, depois que você digitou o Con, a lista do Intellisense vai automaticamente para o início do ítem do Console e você pode pressionar a tecla Tab, Enter ou Spacebar para selecioná-lo In the Code and Text Editor window displaying the

Program.cs file, place the cursor in the Main method after the opening brace, and type Console As you type the letter C at the start of the word Console an IntelliSense list appears This list contains all of the valid C# keywords

and data types that are valid in this context You can either continue typing, or scroll through the list and double-click

the Console item with the mouse Alternatively, after you have typed Con , the Intellisense list will automatically home

in on the Console item and you can press the Tab, Enter, or Spacebar key to select it.

Main deve se parecer com: Main should look like this:

static void Main(string[] args)

{

Console }

NOTA - A Console é uma classe embutida que contém os métodos para exibir

mensagens na tela e obter entrada do teclado Console is a built-in class that contains

the methods for displaying messages on the screen and getting input from the keyboard

2 Digite um ponto imediatamente depois de Console Outra lista do Intellisense aparecerá exibindo os métodos, propriedades e campos da classe console Type a

period immediately after Console Another Intellisense list appears displaying the methods, properties, and fields of the Console class

3 Enrole para baixo pela lista até que WriteLine seja selecionado, e então pressione Enter Alternativamente, você poderá continuar a digitação até que WriteLine seja selecionado e então pressionar Enter Scroll down through the list until

Trang 20

WriteLine is selected, and then press Enter Alter-natively, you can continue typing until WriteLine is selected and

then press Enter

A lista do IntelliSense se fecha e o método WriteLine é acrescentado ao arquivo fonte Main deve se parecer agora com: The IntelliSense list closes, and the WriteLine method is added to the source file Main should now look like this:

static void Main(string[] args)

Esta forma exibe os parâmetros do método WriteLine Na realidade, Write Line é

um método sobrecarregado, significando que Console contém mais de um método nomeado Write Line Cada versão do método WriteLine pode ser usada para produzir tipos diferentes de dados (Os métodos sobrecarregados são discutidos no Capítulo 3) Main deve se parecer agora com: This tip displays the parameters of the WriteLine method In fact, WriteLine is an overloaded method , meaning that Console contains more than one method named

Write Line Each version of the WriteLine method can be used to output different types of data (Overloaded

methods are discussed in Chapter 3.) Main should now look like this:

static void Main(string[] args)

overloaded versions of WriteLine

5 Digite o parêntese fechado, seguido por um ponto-e-vírgula Type a close parenthesis, followed by a semicolon

Main deve se parecer agora com: Main should now look like this:

static void Main(string[] args)

{

Console.WriteLine();

}

6 Digite a string "Hello World" entre os parênteses da esquerda e da direita Type

the string "Hello World" between the left and right parentheses.

Main deve se parecer agora com: Main should now look like this:

static void Main(string[] args)

{

Console.WriteLine("Hello World");

}

DICA Pegar o hábito de digitar pares de caracteres duplos, como ( e ) e { e

}, antes de preencher os seus conteúdos É fácil de esquecer do caractere final

se você esperar até depois que você digitar os conteúdos Get into the habit of typing

Trang 21

matched character pairs, such as ( and ) and { and }, before filling in their contents It's easy to forget the

closing character if you wait until after you've entered the contents

Ícones do IntelliSense

O IntelliSense exibe o nome de todo membro de uma classe À esquerda de cada nome do membro está um ícone que descreve o tipo do membro Os ícones e os seus tipos incluem o seguinte: IntelliSense displays the name of every member of a class To the left of each member name is an icon that depicts the type of member The icons and their types include the following:

Ícone - Significado

Palavra-chave do C#

método (discutido no Capítulo 3)

propriedade (discutido no Capítulo 14)

classe (discutido no Capítulo 7)

struct (discutido no Capítulo 9)

enum (discutido no Capítulo 9)

interface (discutido no Capítulo 12)

delegate (discutido no Capítulo 16)

Namespace

NOTA - Você freqüentemente verá linhas de código que contém duas barras

dianteiras seguidas por texto normal Estes são comentários Eles são ignorados pelo compilador, mas é muito útil para o programador porque eles ajudam na documentação do que um programa está fazendo de fato Por exemplo: You will frequently see lines of code containing two forward slashes followed by ordinary text These are comments They are ignored by the compiler, but are very useful for developers because they help document what a program is actually doing For example:

Console.ReadLine(); // Aguarda que o usuário pressione a tecla Enter

Todo o texto dentro das duas barras até o final da linha será saltado pelo compilador Você também pode adicionar comentários de multi-linha que começam com /* O compilador saltará tudo até encontrar o */ que poderia ser muitas linhas abaixo Nós o estamos encorajando ativamente que você documente seu código com tantos comentários quantos forem necessários All text from the two slashes to the end of the line will be skipped by the compiler You can also add multi-line comments starting with /* The compiler will skip everything until it finds a */ sequence, which could be many lines lower down You are actively encouraged to document your code with as many comments as necessary.

Trang 22

Construa e rode uma aplicação console

1 No menú Build, clique em Build Solution Esta ação faz com que o código em C# seja compilado, resultando em um programa que você pode executar As janelas Output aparecem debaixo do Code and Text Editor On the Build menu, click Build Solution This action causes the C# code to be compiled, resulting in a program that you can run The Output windows appears below the Code and Text Editor window.

DICA - Se a janela Output não aparecer, clique no menú View, e então clique

em Output para exibí-lo If the Output window does not appear, click the View menu, and then click Output to display it.

Na janela Output, mensagens semelhante ao mostrado a seguir como o programa está sendo compilado e exibe os detalhes de qualquer erro que aconteça Neste caso, não deve haver nenhum erro ou advertência e o programa deve se construido prosperamente: In the Output window, messages similar to the following show how the program is being compiled and display the details of any errors that have occurred In this case there should be no errors or warnings, and the program should build successfully:

- Build started: Project: TextHello, Configuration: Debug Any CPU Csc.exe /config /nowarn:"1701;1702" /errorreport: prompt /warn:4

Compile complete –- 0 errors, 0 warnings

TextHello -> C:\Documents and Settings\John\My Documents\Microsoft Press\ ============ Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ========

NOTA - Um asterisco depois do nome de arquivo na aba acima do Code and

Text Editor indica que o arquivo foi mudado desde que foi salvo por último Não há nenhuma necessidade para manualmente salvar o arquivo antes de construir porque o comando Build Solution salva o arquivo automaticamente

An asterisk after the file name in the tab above the Code and Text Editor window indicates that the file has been changed since it was last saved There is no need to manually save the file before building because the Build Solution command automatically saves the file.

No menú Debug, clique em Start Without Debugging Uma janela Command abre e roda o programa A mensagem Hello World aparece, e então o programa espera pelo usuário pressionar qualquer tecla, como mostrado no gráfico seguinte: On the

Debug menu, click Start Without Debugging A Command window opens and the program runs The message Hello

World appears, and then the program waits for the user to press any key, as shown in the following graphic:

Assegure-se de que a janela Command que exibe o programa tenha o foco, e então pressione Enter A janela Command fecha e você voltará ao ambiente de programação do Visual Studio 2005 Ensure that the Command window displaying the program has the focus, and then press Enter The Command window closes and you return to the Visual Studio 2005 programming environment.

Trang 23

NOTA - Se você roda o programa usando Start Debugging no menú Debug, a

aplicação roda mas a janela Command fecha imediatamente sem esperar por você pressionar uma tecla If you run the program using Start Debugging on the Debug menu, the application runs but the Command window closes immediately without waiting for you to press a key.

No Solution Explorer, clique no projeto TextHello (não a solution), e então clique no botão Show All Files Enterdas chamadas de bin e obj aparecem sobre os nomes dos arquivos fonte Estas entradas correspondem diretamente aos diretórios nomeados bin e obj no diretório do projeto (\ Meu Documents\Visual CSharp Step

by Step\Chapter 1\TextHello\TextHello) Estes diretórios são criados quando você constrói sua aplicação, e eles contêm a versão executável do programa e alguns outros arquivos In the Solution Explorer, click the TextHello project (not the solution), and then click Show

All Files button Entries named bin and obj appear above the C# source filenames These entries correspond directly

to folders named bin and obj in the project folder (\My Documents\Visual CSharp Step by Step\Chapter 1\TextHello\TextHello) These folders are created when you build your application, and they contain the executable version of the program and some other files.

No Solution Explorer, clique no + à esquerda da entrada de bin Outro diretório nomeado Debug aparecerá In the Solution Explorer, click the + to the left of the bin entry Another folder named Debug appears.

No Solution Explorer, clique no + à esquerda da da entrada de Debug Três entradas chamadas TextHello.exe, TextHello.pdb e TextHello.vshost.exe aparecerão O arquivo TextHello.exe é o programa compilado e é este arquivo que roda quando você clica Start Without Debugging dentro do menú Debug Os outros dois arquivos contêm informações que são usadas pelo Visual Studio 2005 se você rodar seu programa dentro do modo Debug (quando você clica Start Debugging dentro o menú Debug) In the Solution Explorer, click the + to the left of the Debug entry Three entries named TextHello.exe, TextHello.pdb, and TextHello.vshost.exe appear The file TextHello.exe is the compiled program, and it is this file that runs when you click Start Without Debugging in the Debug menu The other two files contain information that is used by Visual Studio 2005 if you run your program in Debug mode (when you click Start Debugging in the Debug menu).

Trang 24

Compilação em Linha de Comando

Você também pode compilar manualmente seus arquivos fontes para um arquivo executável usando a linha de comando do compilador do C#, o csc Primeiro você tem que completar os seguintes passos para montar seu ambiente: You can also compile your source files into an executable file manually by using the csc command-line C# compiler You must first complete the following steps to set up your environment:

1 No Windows menú Iniciar, aponte para Todos os Programas, vá para Microsoft Visual Studio 2005, aponte para Visual Studio Tools, e clique Visual Studio 2005 Command Prompt Uma janela do Command sed abrirá, e o PATH das variáveis do ambiente, o LIB e o INCLUDE são configurados para incluir os locais das várias bibliotecas do NET Framework e utilitários On the Windows Start menu, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio Tools, and click Visual Studio 2005 Command Prompt A

Command window opens, and the envionment variables PATH , LIB , and INCLUDE are configured to include the

locations of the various NET Framework libraries and utilities.

DICA - Você também pode rodar o script de vcvarsall.bat, localizado no

diretório C:\Program Files\Microsoft Visual Studio 8\VC, se você quer configurar as variáveis de ambiente enquanto executa em uma janela de Prompt de Command ordinária You can also run the vcvarsall.bat script, located in the C:\Program Files\Microsoft Visual Studio 8\VC folder, if you want to configure the environment variables while running in an ordinary Command Prompt window

2 Na janela do Prompt de Command do Visual Studio 2005, digite o seguinte comando para ir para o diretório do projeto \ Meus Documents\Microsoft Press\Visual CSharp Step by Step\Chapter 1\TextHello\TextHello: In the Visual Studio

2005 Command Prompt window, type the following command to go to the \My Documents\Microsoft Press\Visual CSharp Step by Step\Chapter 1\TextHello\TextHello project folder:

cd \Documents and Settings\YourName\My Documents\Microsoft

Press\Visual CSharp Step by Step\Chapter 1\TextHello\TextHello

3 Digite o seguinte comando: Type the following command:

Trang 25

TextHello.exe from the C# source file If you don't use the /out command-line option, the executable file takes its

name from the source file and is called Program.exe.

4 Rode o programa digitando o seguinte comando: Run the program by typing the following command:

TextHello

O programa deve rodar exatamente como o anterior, a não ser que você não verá o lembrete "Press any key to continue" The program should run exactly as before, except that you will not see the "Press any key to continue" prompt

Usando Namespaces

O exemplo que você viu anteriormente é um programa muito pequeno Porém, programas pequenos podem crescer logo para programas maiores A medida que

um programa cresce, cria-se dois problemas Primeiro, mais código é mais difícil de

se entender e manter que menos código Segundo, mais código normalmente significa mais nomes; mais nomeação de dados, mais nomeação de métodos e mais nomeação de classes Como o aumento do número de nomes, torna assim a probabilidade da construção do projeto falhar porque dois ou mais nomes podem colidir (especialmente quando o programa usa bibliotecas de terceiros) The example you have seen so far is a very small program However, small programs can soon grow into bigger programs As a program grows, it creates two problems First, more code is harder to understand and maintain than less code Second, more code usually means more names; more named data, more named methods, and more named classes

As the number of names increases so does the likelihood of the project build failing because two or more names clash (especially when the program uses third-party libraries).

No passado, os programadores tentaram resolver o problema da colisão de nomes antepondo nomes com algum tipo de qualificador (ou a configuração de qualificadores) Esta solução não é muito boa porque não é escalável; os nomes ficam mais longos e você gasta mais tempo na escrita do software e mais também

na digitação (há uma diferença) e lendo e re-lendo nomes longos incompreensíveis

In the past, programmers tried to solve the name-clashing problem by prefixing names with some sort of qualifier (or set of qualifiers) This solution is not a good one because it's not scalable; names become longer and you spend less time writing software and more time typing (there is a difference) and reading and re-reading incomprehensibly long names.

Os namespaces ajudam a resolver este problema criando um recipiente nomeado para os outros identificadores, como as classes Duas classes não serão confundidas com o mesmo nome entre si se elas estiverem em namespaces diferente Você pode criar uma classe chamada Greeting dentro do namespace chamado TextHello, como este: Namespaces help solve this problem by creating a named container for other identifiers, such as classes Two classes with the same name will not be confused with each other if they

live in different namespaces You can create a class named Greeting inside the namespace named TextHello, like

Trang 26

Você então pode se referir à classe de Greeting como TextHello.Greeting em seus próprios programas Se outra pessoa também cria uma classe Greeting em um namespace diferente e instala-a em seu computador, seus programas ainda funcionarão como esperado porque elas estarão usando a classe TextHello.Greeting Se você quiser se referir a nova classe Greeting, você tem que especificar que você quer a classe do novo namespace You can then refer to the Greeting class as TextHello.Greeting in your own programs If someone else also creates a Greeting class in a different

namespace and installs it on your computer, your programs will still work as expected because they are using the

TextHello.Greeting class If you want to refer the new Greeting class, you must specify that you want the class from

the new namespace.

É uma boa prática definir todas as suas classes em namespaces, e a plataforma do Visual Studio 2005 segue esta recomendação usando o nome do seu projeto como

o namespace de alto nível O NET Framework Software Developer Kit (SDK) também adere a esta recomendação; toda classe no NET Framework vive dentro

System Isto significa que seu nome completamente qualificado é de fato

System.Console It is good practice to define all your classes in namespaces, and the Visual Studio 2005 environment follows this recommendation by using the name of your project as the top-level namespace The NET Framework Software Developer Kit (SDK) also adheres to this recommendation; every class in the NET Framework

lives inside a namespace For example, the Console class lives inside the System namespace This means that its fully qualified name is actually System.Console.

Claro que, se todas as vezes você tivesse que escrever o nome completamente qualificado de uma classe, isto não seria melhor do que apenas nomeando a classe SystemConsole Felizmente, você pode resolver este problema com uma diretiva using Se você volta ao programa TextHello no Visual Studio 2005 e observa o arquivo Program.cs no editor de Código e Texto, você notará as seguintes declarações: Of course, if you had to write the fully qualified name of a class every time, it would be no better

that just naming the class SystemConsole Fortunately, you can solve this problem with a using directive If you

return to the TextHello program in Visual Studio 2005 and look at the file Program.cs in the Code and Text Editor window, you will notice the following statements:

scope, and you no longer have to explictly qualify objects with the namespace they belong to in the code that follows The three namespaces shown contain classes that are used so often that Visual Studio 2005 automatically adds

these using statements every time you create a new project You can add further using directives to the top of a

source file.

O exercício seguinte demonstra o conceito adicional dos namespaces The following exercise demonstrates the concept of namespaces further.

Tente nomes comuns

1 Na janela do Code and Text Editor, assinale a diretiva using na parte superior de Program.cs: In the Code And Text Editor window, comment out the using directive at the top of Program.cs:

//using System;

Trang 27

2 No menú Build, clique em Build Solution A construção falha, e o painel Output exibe a seguinte mensagem de erro duas vezes (uma vez para cada uso da classe

Console): On the Build menu, click Build Solution The build fails, and the Output pane displays the following

error message twice (once for each use of the Console class):

The name 'Console' does not exist in the current context

3 No painel Output, clique duas vezes na mensagem de erro O identificador que causou o erro é selecionado no arquivo fonte do Program.cs In the Output pane, double- click the error message The identifier that caused the error is selected in the Program.cs source file

DICA - O primeiro erro pode afetar a confiabilidade das mensagens de

diagnóstico subseqüentes Se sua construção tiver mais de uma mensagem diagnóstico, corrija só a primeira, ignore todas as outras, e então reconstrua Esta estratégia funciona melhor se você mantém sua arquivo fonte pequeno e trabalha interativamente, freqüentemente construindo The first error can affect the reliability of subsequent diagnostic messages If your build has more than one diagnostic message, correct only the first one, ignore all the others, and then rebuild This strategy works best if you keep your source files small and work iteratively, building frequently

4 No Code and Text Editor, edite o método Main para usar o nome completamente qualificado System.Console In the Code and Text Editor window, edit the Main method to use the fully qualified name System.Console.

Main deve se parecer com: Main should look like this:

static void Main(string[] args)

{

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

}

NOTA - Quando você digita System., note como os nomes de todos os ítens

do namespace System são exibidos pelo IntelliSense When you type System., notice how the names of all the items in the System namespace are displayed by IntelliSense

No menú Build, clique em Build Solution A construção tem sucesso desta vez Se não tiver, tenha certeza de que Main é exatamente como aparece no código precedente e então tente construir novamente On the Build menu, click Build Solution The

build succeeds this time If it doesn't, make sure Main is exactly as it appears in the preceding code, and then try

building again.

Rode a aplicação para ainda ter certeza de que funciona clicando em Start Without Debugging no menú Debug Run the application to make sure it still works by clicking Start Without Debugging on the Debug menu.

No Solution Explorer, clique no + à esquerda da entrada References Isto exibe osassemblies referenciados pelo Solution Explorer Um assembly é uma biblioteca que contém código escrito por outros programador (como o NET Framework) Em alguns casos, as classes são armazenadas em um namespace em um assembly que tem o mesmo nome (como System), embora isto não tenha que ser o caso - alguns assemblies seguram mais de um namespace Sempre que você usa um namespace,

Trang 28

você também precisa ter certeza de que você referenciou o assembly que contém

as classes para aquele namespace; caso contrário seu programa não será construído (ou executado) In the Solution Explorer, click the + to the left of the References entry This displays the assemblies referenced by the Solution Explorer An assembly is a library containing code written by other developers (such as the NET Framework) In some cases, the classes in a namespace are stored in an

assembly that has the same name (such as System), although this does not have to be the case—some assemblies

hold more than one namespace Whenever you use a namespace, you also need to make sure that you have referenced the assembly that contains the classes for that namespace; otherwise your program will not build (or run).

Criando uma Aplicação Windows

Anteriormente você usou o Visual Studio 2005 para criar e rodar uma aplicação Console básica A plataforma de programação Visual Studio 2005 também contém tudo o que você precisa para criar aplicações Windows gráficas Você pode projetar

a interface do usuário baseada em forms de uma aplicação Windows interactivamente usando o Visual Designer O Visual Studio 2005 então gera as declarações do programa para implementar a interface do usuário que você projetou So far you have used Visual Studio 2005 to create and run a basic Console application The Visual Studio 2005 programming environment also contains everything you'll need to create graphical Windows applications You can design the form-based user interface of a Windows application interactively by using the Visual Designer Visual Studio 2005 then generates the program statements to implement the user interface you've designed.

Desta explicação, segue-se que o Visual Studio 2005 lhe permite manter duas visões da aplicação: a Design View (Visão de Sesign) e a Code View O Code and Text Editor (mostrando as declarações do programa) dobra como a janela Design View (lhe permitindo dispor sua interface do usuário), e você pode trocar entre as duas visões sempre que você quizer From this explanation, it follows that Visual Studio 2005 allows you to maintain two views of the application: the Design View and the Code View The Code and Text Editor window (showing the program statements) doubles as the Design View window (allowing you to lay out your user interface), and you can switch between the two views whenever you want.

No seguinte grupo de exercícios, você aprenderá a criar um programa Windows no Visual Studio 2005 Este programa exibirá um simples form que contém um text box onde você pode entrar com seu nome e um botão que, quando clicado, exibe uma saudação personalizada em um message box Use o Visual Designer para mudar as propriedades de controle; use o Visual Designer para redimensionar o form; use o Visual Designer para mudar as propriedades de controle; use o Visual Designer a redimensionar o form; escreva o código para responder a um clique do botão; e rode seu primeiro programa Windows In the following set of exercises, you'll learn how

to create a Windows program in Visual Studio 2005 This program will display a simple form containing a text box where you can enter your name and a button that, when clicked, displays a personalized greeting in a message box You will use the Visual Designer to create your user interface by placing controls on a form; inspect the code generated by Visual Studio 2005; use the Visual Designer to change the control properties; use the Visual Designer

to resize the form; write the code to respond to a button click; and run your first Windows program.

Crie um Projeto Windows no Visual Studio 2005

No menú File, aponte para New e então clique Project A dialog box do New Project abrirá On the File menu, point to New, and then click Project The New Project dialog box opens.

No painel Project Types, clique em Visual C# In the Project Types pane, click Visual C#

No painel Templates (Modelos), clique no ícone Windows Applications In the Templates pane, click the Windows Application icon

Trang 29

Assegure-se de que o campo Location se refere ao seu diretório \ Meu Documents\Visual CSharp Passo por Step\Chapter 1 Ensure that the Location field refers to your \My Documents\Visual CSharp Step by Step\Chapter 1 folder

No campo Name, digite WinFormHello In the Name field, type WinFormHello

No campo Solutions, assegure-se de que o Create new Solution (Crie Nova Solução) foi selecionado Esta ação cria uma nova solução para assegurar a aplicação Windows A alternativa, Add to Solution (Acrescente à Solução), acrescentará ao projeto à solução TextHello In the Solutions field, ensure that Create new Solution is selected This action creates a new solution for holding the Windows application The alternative, Add to Solution , will add the project to the TextHello solution.

Clique no OK O Visual Studio 2005 fecha sua aplicação atual (incitando à salvá-lo primeiro se necessário) e cria e exibe um form Windows vazio na janela Design View Click OK Visual Studio 2005 closes your current application (prompting you to save it first of necessary) and creates and displays an empty Windows form in the Design View window.

No exercício seguinte, você usará o Visual Designer para acrescentar três controles

ao Windows form e examinar algum código do C# gerado pelo Visual Studio 2005 para implementar estes controles automaticamente In the following exercise, you'll use the Visual Designer to add three controls to the Windows form and examine some of the C# code automatically generated by Visual Studio 2005 to implement these controls.

Crie a interface do usuário

1 Clique na aba da Toolbox que aparece à esquerda do form no Design View A Toolbox aparecerá, escondendo parcialmente o form e exibindo os vários

Trang 30

componentes e controles que você pode colocar em um form Windows Click the Toolbox tab that appears to the left of the form in the Design View The Toolbox appears, partially obscuring the form and displaying the various components and controls that you can place on a Windows form

2 Na Toolbox, clique no sinal + do Common Control (Controles Comuns) para exibir uma lista de controles que são usados pela maioria das aplicações Windows Forms In the Toolbox, click the + sign by Common Controls to display a list of controls that are used by most Windows Forms applications.

3 Clique em Label, e então clique na parte visível do form Um controle Label é acrescentado ao form e a Toolbox desaparece da visão Click Label, and then click the visible

part of the form A Label control is added to the form, and the Toolbox disappears from view

DICA - Se você quiser que a Toolbox permaneça visível mas que não esconda

qualquer parte do form, clique no botão Auto Hide, à direita na barra de títulos

da Toolbox (ele se parece com um alfinete) A Toolbox aparecerá permanentemente no lado esquerdo da janela do Visual Studio 2005 e o Design View encolhe para acomodá-lo (Você pode perder muito espaço se você tivesse uma tela de baixa-resolução.) Clicando no botão Auto Hide faz com que, mais uma vez, a Toolbox desapareça If you want the Toolbox to remain visible but not hide any part of the form, click the Auto Hide button to the right in Toolbox title bar (it looks like a pin) The Toolbox appears permanently on the left side of the Visual Studio 2005 window, and the Design View shrinks to accommodate it (You might lose a lot of space if you have a low-resolution screen.) Clicking the Auto Hide button once more causes the Toolbox to disappear again.

4 O controle Label no form provavelmente não está exatamente onde você quer que ele esteja Você pode clicar e pode arrastar os controles que você acrescenta a

um form para reposicioná-los Usando esta técnica, mova o controle Label de forma que ele seja posicionado para o canto de superior-esquerdo do form (A colocação exata não é crítica para esta aplicação) The Label control on the form is probably not exactly

where you want it You can click and drag the controls you have added to a form to reposition them Using this

technique, move the Label control so that it is positioned towards the upper-left corner of the form (The exact

placement is not critical for this application.)

5 No menú View, clique na janela Properties Esta janela aparece ao lado da tela à direita A janela Properties lhe permite configurar as propriedades dosítens em um projeto Ela é sensível ao contexto, em que ela exibe as propriedades para o ítem atualmente selecionado Se você clicar em qualquer lugar no form mostrado na Design View, você verá que as janelas das Properties exibe as propriedades para a próprio form Se você clicar no controle Label, a janela exibe as propriedades ao invés de para o Label On the View menu, click Properties Window The Properties window appears on the right side of the screen The Properties window allows you to set the properties for items in a project It is context sensitive, in that it displays the properties for the currently selected item If you click anywhere on the form displayed

in the Design View, you will see that the Properties windows displays the properties for the form itself If you click the

Label control, the window displays the properties for the label instead.

6 Clique no controle Label no form Na janela Properties, localize a propriedade Text, mude de label1 para Entre com Seu Nome, e então pressione Enter No form,

o texto do Label muda para Entre com Seu Nome Click the Label control on the form In the Properties window, locate the Text property, change it from label1 to Enter your name , and then press Enter On the form, the label's text changes to Enter Your Name

DICA - Por padrão, as propriedades são exibidas em categorias Se você

preferir exibí-las em ordem alfabética, clique no botão Alphabetical que aparece sobre a lista de propriedades By default, the properties are displayed in categories

If you prefer to display the properties in alphabetical order, click the Alphabetical button that appears above the properties list

Trang 31

7 Mostre a Toolbox novamente Clique em TextBox, e então clique no form Um controle TextBox é acrescentado ao form Mova o controle TextBox do form para que ele fique diretamente debaixo do controle Label Display the Toolbox again Click

TextBox, and then click the form A TextBox control is added to the form Move the TextBox control so that it is directly underneath the Label control.

DICA - Quando você arrastar um controle em um form, manipuladores de

alinhamento aparecem automaticamente quando o controle é alinhado vertical

ou horizontalmente com outros controles Isto lhe dá uma sugestão visual rápida para ter certeza de que os controles estão nitidamente alinhados certos When you drag a control on a form, alignment handles appear automatically when the control becomes aligned vertically or horizontally with other controls This give you a quick visual cue for making sure that controls are lined up neatly

8 Enquanto o controle TextBox é selecionado, localize a propriedade Text na janela Properties, digite aqui, e então pressione Enter No form, a palavra aqui aparece

na text box While the TextBox control is selected, locate the Text property in the Properties window, type here , and then press Enter On the form, the word here appears in the text box

9 Na janela Properties, ache a propriedade (Nome) O Visual Studio 2005 dá aos controles e forms nomes padrões, embora eles sejam um bom ponto de partida, sempre não é muito significante Mude o nome do controle TextBox para userName In the Properties window, find the (Name) property Visual Studio 2005 gives controls and forms

default names, which, although they are a good starting point, are not always very meaningful Change the name of

the TextBox control to userName

NOTA - Nós falaremos mais sobre a nomeação de convenções para controles

e variáveis no "Capítulo 2 Trabalhando com Variáveis, Operadores e

Expressões" We will talk more about naming conventions for controls and variables in Chapter 2,

“Working with Variables, Operators, and Expressions.”

Exiba a Toolbox novamente, clique em Button, e então clique no form Arraste o controle Button à direita do controle TextBox no form de maneira que ele fique horizontalmente alinhado com a text box Display the Toolbox again, click Button, and then click

the form Drag the Button control to the right of the TextBox control on the form so that it is aligned horizontally with

the text box.

Usando a janela Properties, mude a propriedade Text do controle Button para OK Mude sua propriedade (Name) para ok A legenda do botão muda Using the Properties

window, change the Text property of the Button control to OK Change its (Name) property to ok The caption on the

button changes.

Clique no form Form1 na janela Design View Note que a alça de redimensionamento (quadrados pequenos) apareça na mais baixa extremidade, a extremidade à direita e o canto do fundo da direita do form Click the Form1 form in the Design View window Notice that resize handles (small squares) appear on the lower edge, the right-hand edge, and the right-hand bottom corner of the form

Mova o ponteiro do mouse por sobre a alça de redimensionamento O ponteiro muda para uma seta encabeçada dupla e diagonalmente Move the mouse pointer over the resize handle The pointer changes to a diagonal double headed arrow

Pressione o botão do mouse esquerdo, e arraste o ponteiro para redimensionar o form Pare o arrastamento e liberte o botão do mouse quando o espaçamento ao redor dos controles for mais ou menos igual Hold down the left mouse button, and drag the pointer to resize the form Stop dragging and release the mouse button when the spacing around the controls is roughly equal.

Trang 32

DICA - Você pode redimensionar muitos controles em um form selecionando o

controle e arrastando uma das alças de redimensionamento que aparecem nos cantos do controle Nota que um form somente tem uma manivela de redimensionamento, considerando que a maioria dos controles tem quatro (um em cada canto) Em um form, qualquer alça de redimensionamento diferente daquele do canto abaixa à direita, seria supérfluo Também note que

um pouco de controles, como os controles Label, são automaticamente do tamanho baseado nos seus conteúdos e não pode ser redimensionados pelo arrastamento You can resize many controls on a form by selecting the control and dragging one of

the resize handles that appears in the corners of the control Note that a form has only one resize handle, whereas most controls have four (one on each corner) On a form, any resize handles other than the one in

the lower-right corner would be superfluous Also note that some controls, such as Label controls, are

automatically sized based on their contents and cannot be resized by dragging them.

O form deve agora ser semelhante àquele do gráfico seguinte The form should now look similar to the one in the following graphic.

15 No Solution Explorer, dê um clique direito no arquivo Form1.cs, e então clique em View Code O arquivo fonte Form1.cs aparecerá no Code and Text Editor

In the Solution Explorer, right-click the file Form1.cs, and then click View Code The Form1.cs source file appears in the Code and Text Editor window

Existem agora duas abas chamadas Form1.cs sobre a janela Code and Text Editor/Design View Você pode clicar naquele sufixado com o [Design] para retornar para a janela Design View a qualquer hora There are now two tabs named Form1.cs above the Code and Text Editor/Design View window You can click the one suffixed with [Design] to return to Design View window at any time.

O Form1.cs contém algum código gerado automaticamente pelo Visual Studio 2005 Você deve notar os seguintes elementos: Form1.cs contains some of the code automatically generated by Visual Studio 2005 You should note the following elements:

diretiva using using directives

O Visual Studio 2005 colocou vários diretivas using na parte superior do arquivo fonte (mais do que para o exemplo anterior) Por exemplo: Visual

Studio 2005 has written a number of using directives at the top of the source file (more than for the previous

example) For example:

using System.Windows.Forms;

Os namespaces adicionais contêm as classes e controles usados quando se constrói aplicação gráficas, por exemplo, as classes do TextBox, do Label e

do Button The additional namespaces contain the classes and controls used when building graphical

applications—for example, the TextBox , Label , and Button classes.

• O namespace

Trang 33

O Visual Studio 2005 usou o nome do projeto como o nome do namespace

de alto nível: Visual Studio 2005 has used the name of the project as the name of the top-level namespace:

NOTA - Por enquanto, ignore a palavra chave parcial nesta classe Eu

descreverei seu propósito brevemente For the time being, ignore the partial keyword in this class I will describe its purpose shortly

Esta classe implementa o form que você criou no Design View (As classes serão discutidas no Capítulo 7) This class implements the form you created in the Design View (Classes are discussed in Chapter 7.)

Aí não pareça ser muito diferente do código um pouco conhecido como um construtor que chama um método chamado InitializeComponent, nada mais (Um construtor é um método especial com o mesmo nome da classe Ele é executado quando o form é criado e pode conter código para inicializar o form Também os construtores são discutidos no Capítulo 7) Porém, o Visual Studio 2005 está executando um truque e está escondendo algumas coisas de você, como eu demonstrarei agora There does not appear to be much else in this class—there is a little bit of code

known as a constructor that calls a method called InitializeComponent , but nothing else (A constructor is a special

method with the same name as the class It is executed when the form is created and can contain code to initialize the form Constructors are also discussed in Chapter 7.) However, Visual Studio 2005 is performing a sleight of hand and is hiding a few things from you, as I will now demonstrate.

Em uma aplicação Windows Forms, o Visual Studio 2005 gera na verdade potencialmente uma grande quantidade de código Este código executa operações como criar e exibir o form quando a aplicação roda, e criar e posicionar os vários controles no form Porém, este código pode mudar assim que você você acrescente controles a um form e mude as suas propriedades Não é esperado que você mude este código (realmente, qualquer mudança que você provavelmente faça, será sobreescrito da próxima vez que você editar o form no Design View), então o Visual Studio Visual 2005 esconde isto de você In a Windows Forms application, Visual Studio 2005 actually generates a potentially large amount of code This code performs operations such as creating and displaying the form when the application starts, and creating and positioning the various controls on the form However, this code can change as you add controls to a form and change their properties You are not expected to change this

Trang 34

code (indeed, any changes you make are likely to be overwritten the next time you edit the form in the Design View),

so Visual Studio 2005 hides it from you.

Para mostrar o código escondido, volte ao Solution Explorer, e clique no o botão Show All Files Os diretórios bin e obj aparecem, muito como o que fizeram com a aplicação Console que você desenvolveu na primeira parte deste capítulo Porém, observe que o Form1.cs agora tem um sinal de + próximo a ele Se você clicar no sinal de +, você verá um arquivo chamado Form1.Designer.cs e um arquivo chamado Form1.resx To display the hidden code, return to the Solution Explorer, and click the Show All Files button The bin and obj folders appear, much as they did with the Console application you developed in the first part of this chapter However, notice that Form1.cs now has a + sign next to it If you click this + sign, you see a file called Form1.Designer.cs, and a file called Form1.resx.

Clique duas vezes no arquivo Form1.Designer.cs para mostrar seus conteúdos no Code and Text Editor Você verá o restante do código para a classe Form1 neste arquivo O C# lhe permite dividir o código para uma classe por múltiplos arquivos fonte, contanto que cada parte desta classe seja marcada com a palavra chave parcial Este arquivo inclui uma região intitulada de região Windows Form Designer geradora de código Ampliando esta região clicando no sinal de +, revela o código criado e mantido pelo Visual Studio 2005 quando você edita um form que usa a janela Design View Os conteúdos atuais deste arquivo incluem: Double-click the file Form1.Designer.cs to display its contents in the Code and Text Editor window You will see the remaining code for the Form1 class in this file C# allows you to split the code for a class across multiple source files, as long as each

part of the class is marked with the partial keyword This file includes a region labelled Windows Form Designer

generated code Expanding this region by clicking the + sign reveals the code created and maintained by Visual

Studio 2005 when you edit a form using the Design View window The actual contents of this file include:

• O método InitializeComponent

Este método é mencionado no arquivo Form1.cs As declarações dentro deste método configuraram as propriedades dos controles que você acrescentou ao form no Design View (Os métodos são discutidos no Capítulo 3) Algumas das declarações neste método corresponde às ações que você executa usando a janela Properties são mostrados abaixo: This method is mentioned in the file Form1.cs The statements inside this method set the properties of the controls you added to the form in the Design View (Methods are discussed in Chapter 3.) Some of the statements in this method that correspond

to the actions you performed using the Properties window are shown below:

private void InitializeComponent()

{

this.label1 = new System.Windows.Forms.Label();

this.userName = new System.Windows.Forms.TextBox();

this.ok = new System.Windows.Forms.Button();

Trang 35

}

• Três campos

O Visual Studio 2005 criou três campos dentro da classe Form1 Estes campos aparecem perto do fim do arquivo: Visual Studio 2005 has created three fields

inside the Form1 class These fields appear near the end of the file:

private System.Windows.Forms.Label label1;

private System.Windows.Forms.TextBox userName;

private System.Windows.Forms.Button ok;

Estes campos implementam os três controles que você acrescentou ao form em Design View (Os Campos são discutidos no Capítulo 7) These fields implement the three controls you added to the form in Design View (Fields are discussed in Chapter 7.)

Vale declarar novamente que, embora este arquivo seja interessante de se ver, você nunca deverá editar seus conteúdos O Visual Studio 2005 atualiza este arquivo automaticamente quando você fizer mudanças pelo Design View Qualquer código que você precise escrever, deve ser colocado no arquivo Form1.cs It is worth restating that although this file is interesting to look at, you should never edit its contents yourself Visual Studio 2005 automatically updates this file when you make changes in the Design View Any code that you need to write yourself should be placed in the Form1.cs file.

Até este ponto você poderia estar desejando saber onde o método Main está e como o form é exibido quando a aplicação é executada; lembre-se de que o Main

define o ponto ao qual o programa inicia No Solution Explorer, você deve notar outro arquivo fonte chamado Program.cs Se você clicar duas vezes neste arquivo o código seguinte aparece no Code and Text Editor: At this point you might well be wondering

where the Main method is and how the form gets displayed when the application runs; remember that Main defines

the point at which the program starts In the Solution Explorer, you should notice another source file called Program.cs If you double-click this file the following code appears in the Code and Text Editor window:

Você ignore a maior parte deste deste código Porém, a declaração fundamental é:

You can ignore most of this code However, the key statement is:

Trang 36

Escreva o código para o botão OK

Clique na aba Form1.cs[Design] sobre o Code and Text Editor para mostrar o Form1 no Design View Click the Form1.cs[Design] tab above the Code and Text Editor window to

display Form1 in the Design View

Mova o ponteiro do mouse sobre o botão do OK no form, e então clique duas vezes

no botão O arquivo fonte do Form1.cs aparece no Code and Text Editor O Visual Studio 2005 adicionou um método chamado ok_Click à classe Form1 (Também acrescentou uma declaração ao método InitializeComponent no arquivo Form1.Designer.cs para chamar o ok_Click automaticamente quando o botão do OK for clicado Ele faz isto usando um tipo de delegado; os delegados são discutidos no

"Capítulo 16, Delegados e Eventos") Move the mouse pointer over the OK button on the form, and then double-click the button The Form1.cs source file appears in the Code and Text Editor window Visual Studio

2005 has added a method called ok_Click to the Form1 class (It has also added a statement to the

InitializeComponent method in the Form1.Designer.cs file to automatically call ok_Click when the OK button is

clicked It does this by using a delegate type; delegates are discussed in Chapter 16, “Delegates and Events.”)

Digite a declaração do MessageBox mostrada abaixo dentro do método ok_Click O método completo deve se parecer com: Type the MessageBox statement shown below inside the

ok_Click method The complete method should look like this:

private void ok_Click(object sender, System.EventArgs e)

Você agora está pronto para rodar seu primeiro programa Windows You're now ready

to run your first Windows program

Rode o programa Windows

No menú Debug, clique em Start Without Debugging O Visual Studio 2005 salva seu trabalho, compila seu programa, e o executa O form do Windows aparece:

On the Debug menu, click Start Without Debugging Visual Studio 2005 saves your work, compiles your program, and runs it The Windows form appears:

Entre com seu nome e então clique no OK Uma message box aparece dando-lhe boas-vindas pelo seu nome Enter your name, and then click OK A message box appears welcoming you by name.

Trang 37

Clique no OK da message box A message box se fechará Click OK in the message box The message box closes.

Na janela Form1, clique no botão Close (o X no canto de superior-direito do form)

A janela Form1 se fechará In the Form1 window, click the Close button (the X in the upper-right corner

of the form) The Form1 window closes.

• Se você quizer continuar no próximo capítulo If you want to continue to the next chapter

Mantenha Visual Studio 2005 rodando, e vire até o Capítulo 2 Keep Visual Studio 2005 running, and turn to Chapter 2

• Se você quizer encerrar o Visual Studio 2005 agora If you want to exit Visual Studio

2005 now

No menú File, clique Exit Se você vê um dialog box Save, clique Sim para salvar seu trabalho On the File menu, click Exit If you see a Save dialog box, click Yes to save your work.

Capítulo 1 Rápida Referência

Selecione um diretório para o arquivo do projeto

no box Location Escolha um nome para o projeto Clique no OK On the File menu, point to New, and then click Project to open the New Project

Trang 38

dialog box For the project type, select Visual C# For the template, select Console Application Select a directory for the project files in the Location box Coose

a name for the project Click OK.

Application Selecione um diretório para o arquivo do projeto no box local Escolha um nome para o projeto Clique o OK On the File menu, point to New, and then click Project to open the New Project dialog box For the project type, select Visual C# For the template, select Windows Application

Select a directory for the project files in the location box

Choose a name for the project Click OK.

Trang 39

Capítulo 2 - Trabalhando com Variáveis, Operadores

• Usar as variáveis para armazenar informações Use variables to store information

• Trabalhar com tipos de dados primitivos Work with primitive data types.

• Usar os operadores matemáticos como o sinal de adição (+) e o sinal de subtração (-) Use arithmetic operators such as the plus sign (+) and the minus sign (–).

• Incrementar e decrementar variáveis Increment and decrement variables.

No Capítulo 1, "Bem-vindo ao C# ", você aprendeu a usar a plataforma de programação Visual Studio 2005 para construir e rodar um programa de Console e uma aplicação Windows Forms Neste capítulo, você será apresentado aos elementos da sintaxe e da semântica do Visual C#, inclusive as declarações, as palavras chaves e os identificadores Você estudará os tipos primitivos que são construídos na linguagem C# e as características dos valores que cada tipo manipula Você também verá como declarar e usar variáveis locais (variáveis que

só existem dentro de uma função ou outra seção de pequeno código), vai aprender sobre os operadores matemáticos que o C# fornece, vai aprender a usar os operadores para manipular valores e vai aprender a controlar expressões que contêm dois ou mais operadores In Chapter 1, “Welcome to C#,” you learned how to use the Microsoft Visual Studio 2005 programming environment to build and run a console program and a Windows Forms application In this chapter, you'll be introduced to the elements of Microsoft Visual C# syntax and semantics, including statements, keywords, and identifiers You'll study the primitive types that are built into the C# language and the characteristics of the values that each type holds You'll also see how to declare and use local variables (variables that exist only within a function or other small section of code), learn about the arithmetic operators that C# provides, learn how to use operators to manipulate values, and learn how to control expressions containing two or more operators.

Entendendo as Declarações

Uma declaração é um comando que executa uma ação As declarações são encontradas dentro de métodos Você aprenderá mais sobre os métodos no

"Capítulo 3, Escrevendo Métodos e Aplicando escopo", mas por agora, pense em

um método como uma sucessão nomeada de declarações dentro de uma classe Main que foi introduzido no capítulo anterior é um exemplo de um método As

Trang 40

declarações em C# tem que seguir um conjunto bem definido de regras Estas regras são coletivamente conhecidas como sintaxe (Em contraste, a especificação

do que faz as declarações é coletivamente conhecido como semântica) Uma das mais simples e a mais importante sintaxe que rege estados no C# é que, você tem que terminar todas as declarações com um ponto-e-vírgula Por exemplo, sem seu ponto-e-vírgula final, a seguinte declaração não compilará: A statement is a command that

performs an action Statements are found inside methods You'll learn more about methods in Chapter 3, “Writing Methods and Applying Scope,” but for now, think of a method as a named sequence of statements inside a class

Main, which was introduced in the previous chapter, is an example of a method Statements in C# must follow a

well-defined set of rules These rules are collectively known as syntax (In contrast, the specification of what statements

do is collectively known as semantics.) One of the simplest and most important C# syntax rules states that you must

terminate all statements with a semicolon For example, without its terminating semicolon, the following statement won't compile:

Console.WriteLine("Hello World");

DICA - O C# é uma linguagem de formato livre, o que significa que os

espaços em branco, como um caractere de espaço ou uma nova linha, não é significante excleto como um separador Em outras palavras, você é livre para dispor suas declarações em qualquer estilo que você escolha Um estilo de layout simples e consistente torna um programa mais fácil de se ler e de se entender C# is a “free format” language, which means that white space, such as a space character or a new line, is not significant except as a separator In other words, you are free to lay out your statements in any style you choose A simple, consistent layout style makes a program easier to read and understand.

O segredo para se programar bem em qualquer linguagem está em aprender a sua sintaxe e a sua semântica e então usá-la de um modo natural e idiomático Esta caminho torna seus programas legíveis e fáceis de seerem modificados Nos capítulos ao longo deste livro, você verá exemplos das declarações mais importantes do C# The trick to programming well in any language is learning its syntax and semantics and then using the language in a natural and idiomatic way This approach makes your programs readable and easy to modify In the chapters throughout this book, you'll see examples of the most important C# statements

Usando Identificadores

Os identificadores são os nomes você usa para identificar os elementos em seus

programas Em C#, você tem que aderir às seguintes regras da sintaxe ao escolher

identificadores: Identifiers are the names you use to identify the elements in your programs In C#, you must

adhere to the following syntax rules when choosing identifiers:

• Você pode usar somente letras (maiúscula e minúscula), dígitos e caractere underline Um identificador tem que começar com uma letra (uma underline

é considerada uma letra) Por exemplo, result, _score, footballTeam e

plan9 são todos identificadores válidos, considerando que result%,

footballTeam$ e 9plan não são You can use only letters (uppercase and lowercase), digits, and underscore characters An identifier must start with a letter (an underscore is considered a letter)

For example, result, _score, footballTeam, and plan9 are all valid identifiers, whereas result%,

footballTeam$, and 9plan are not.

IMPORTANTE - O C# é uma linguagem caso-sensível: footballTeam e

FootballTeam não são o mesmo identificador C# is a case-sensitive language:

footballTeam and FootballTeam are not the same identifier.

Ngày đăng: 28/03/2014, 20:20

TỪ KHÓA LIÊN QUAN

w