Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 3 TYPES, STORAGE, AND VARIABLES

Multiple-Variable Declarations

You can declare multiple variables in a single declaration statement.

The variables in a multiple-variable declaration must all be of the same type.

The variable names must be separated with commas. Initializers can be included with the variable names.

For example, the following code shows two valid declaration statements with multiple variables. Notice that the initialized variables can be mixed with uninitialized variables as long as they’re separated by commas. The last declaration statement shown is invalid because it attempts to declare different types of variables in a single statement.

// Variable declarations--some with initializers, some without

int

var3 = 7, var4, var5 = 3;

double

var6, var7 = 6.52;

 

Type

Different type

 

 

int var8, float var9;

// Error! Can't mix types (int and float)

Using the Value of a Variable

A variable name represents the value stored by the variable. You can use the value by using the variable name.

For example, in the following statement, the value of var2 is retrieved from memory and placed at the position of the variable.

Console.WriteLine("{0}", var2);

Static Typing and the dynamic Keyword

One thing you’ll have noticed is that every variable includes the type of the variable, allowing the compiler to determine the amount of memory it will require at runtime and which parts should be stored in the stack and which in the heap. The type of the variable is determined at compile time and cannot be changed at runtime. This is called static typing.

Not all languages, though, are statically typed. Many, including such scripting languages as IronPython and IronRuby, are dynamically typed. That is, the type of a variable might not be resolved until runtime. Since these are .NET languages, C# programs need to be able to use assemblies written in these languages.

To solve the problem that C# needs to be able to resolve at compile time a type referenced in an assembly that doesn’t resolve its types until runtime, the C# language designers added the keyword dynamic to the language. The dynamic keyword represents a specific, actual C# type that knows how to resolve itself at runtime. That is, it’s statically typed as dynamic!

This satisfies both constraints. The C# compiler can resolve the keyword to an actual type, and the type object can resolve itself to the target assembly’s type at runtime.

45

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]