Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (703.8 KB, 65 trang )
<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>
<b>Microsoft</b>
<b>Microsoft</b>
<b>double ComputeAvg( int param1, int param2 )</b>
<b>{</b>
<b>return (param1 + param2) / 2.0;</b>
<b>}</b>
<b>object ComputeAvg( object param1, object param2 )</b>
<b>{</b>
<b>return ((int) param1 + (int) param2) / 2.0;</b>
<b>}</b>
<b>ComputeAvg accepts two </b>
<b>integers and returns a double. If </b>
<b>passing an instance of Apple </b>
<b>type, the compiler will complain </b>
<b>and stop</b>
<b>Convert objects into </b>
<b>integers</b>
<i>object</i><b>keyword: an alias of </b>
<b>System.Object class</b>
<b>Microsoft</b>
• Eg: the + operator can mean string concatenation using with string operands
• When an expression contains multiple operators, the <i>precedence</i> of the
operators controls the order in which the individual operators are evaluated
• Entries at the top of the table have higher precedence
<b>Microsoft</b>
<b>Category</b> <b>Expression</b> <b>Description</b>
Primary x.m Member access
x(...) Method and delegate invocation
x[...] Array and indexer access
x++ Post-increment
x-- Post-decrement
new T(...) Object and delegate creation
new T(...){...} Object creation with initializer
new {...} Anonymous object initializer
new T[...] Array creation
typeof(T) Obtain System.Type object for T
checked(x) Evaluate expression in checked context
unchecked(x) Evaluate expression in unchecked context
default(T) Obtain default value of type T
delegate {...} Anonymous function (anonymous method)
<b>Category</b> <b>Expression</b> <b>Description</b>
Unary +x Identity
-x Negation
!x Logical negation
~x Bitwise negation
++x Pre-increment
--x Pre-decrement
(T)x Explicitly convert x to type T
Multiplicative x * y Multiplication
x / y Division
x % y Remainder
Additive x + y Addition, string concatenation, delegate combination
x – y Subtraction, delegate removal
Shift x << y Shift left
<b>Microsoft</b>
<b>Category</b> <b>Expression</b> <b>Description</b>
Relational and
type testing
x < y Less than
x > y Greater than
x <= y Less than or equal
x >= y Greater than or equal
x is T Return true if x is a T, false otherwise
x as T Return x typed as T, or null if x is not a T
Equality x == y Equal
x != y Not equal
Logical AND x & y Integer bitwise AND, boolean logical AND
<b>Microsoft</b>
<b>A block: consists of a list of statements written between the </b>
<b>delimiters { and }</b>
<i><b>Declaration statements: are used to declare local variables and </b></i>
constants
<b>12</b>
{x=69;y=96}
int a;
<i><b>Epression statements are used to evaluate expressions</b></i>
<i><b>Selection statements are used to select one of a number of </b></i>
possible statements for execution based on the value of some
expression – <b>if, switch</b>
<i><b>Iteration statements are used to repeatedly execute an </b></i>
embedded statement – <b>while</b>, <b>do</b>, <b>for</b>, <b>foreach</b>
while (i ++< Length) {
if(continue == true) {x=69;}
else {x=96;}
<b>Microsoft</b>
<i><b>Jump statements are used to transfer control -</b></i> <b>break, </b>
<b>continue, goto, throw, return, and yield</b>
The <b>try...catch</b> statement is used to catch exceptions that
occur during execution of a block, and the <b>try...finally</b>
statement is used to specify finalization code that is always
executed, whether an exception occurred or not
<b>14</b>
1. while (true) {
2. int n = Console.Read();
3. if (n == 69) break;
4. Console.WriteLine(n);
The <b>checked</b> and <b>unchecked</b> statements are used to control
the overflow checking context for integral-type arithmetic
operations and conversions
The <b>lock</b> statement is used to obtain the mutual-exclusion lock
for a given object, execute a statement, and then release the
lock
<b>Microsoft</b>
On the heap: only if they are members of reference types or if they
are boxed
<b>Microsoft</b>
<b>Microsoft</b>
<b>20</b>
int i = 123;
string s = "Hello world";
123
i
s <sub>"Hello world"</sub>
Value
Type
Reference
Type
<b>Microsoft</b>
<b>struct Rectangle</b>
<b>{</b>
<b>public ShapeInfo rectInfo;</b>
<b>public int rectTop, rectLeft, rectBottom, rectRight;</b>
<b>public Rectangle(string info, int top, int left, int bottom, int right)</b>
<b>{</b>
<b>rectInfo = new ShapeInfo(info);</b>
<b>rectTop = top; rectBottom = bottom;</b>
<b>rectLeft = left; rectRight = right;</b>
<b>}</b>
<b>public void Display()</b>
<b>{</b>
<b>Console.WriteLine("String = {0}, Top = {1}, Bottom = {2}," +</b>
<b>"Left = {3}, Right = {4}",</b>
<b>rectInfo.infoString, rectTop, rectBottom, rectLeft, rectRight);</b>
<b>}</b>
<b>Value type</b>
<b>The Rectangle structure </b>
<b>contains a reference </b>
<b>type member</b>
static void ValueTypeContainingRefType()
{
Console.WriteLine("-> Creating r1");
Rectangle r1 = new Rectangle("First Rect", 10, 10, 50, 50);
.
Console.WriteLine("-> Assigning r2 to r1");
Rectangle r2 = r1;
Console.WriteLine("-> Changing values of r2");
r2.rectInfo.infoString = "This is new info!";
r2.rectBottom = 4444;
.
r1.Display();
Assign a new
Rectangle to
r1
Change some
values of r2.
<b>Microsoft</b>
Static variables.
Instance variables of class instances.
Array elements.
<b>Microsoft</b>
All value types implicitly declare a public parameterless instance
<i><b>constructor called the default constructor</b></i>
<i><b>Default constructor returns the default value for the value type:</b></i>
<b>26</b>
<b>Value Type</b> <b>Default Value</b>
<b>sbyte, byte, short, ushort, int, uint, </b>
<b>long, and ulong</b>
0
<b>char</b> '\x0000'
<b>Value Type</b> <b>Default Value</b>
<b>float</b> 0.0f
<b>double</b> 0.0d
<b>decimal</b> 0.0m
<b>bool</b> false
<i>enum-type E</i> 0, converted to the type E
<b>Microsoft</b>
<b>Microsoft</b>
using System;
using System.Collections.Generic;
public class EntryPoint
{
static void Main()
{
var myList = new List<int>();
myList.Add( 1 );
myList.Add( 2 );
myList.Add( 3 );
foreach( var i in myList )
{
Console.WriteLine( i );
}
}
}
An implicitly typed
variable declaration must
var newValue; // emits error CS0818
var a = 2, b = 1;
var x, y = 4;
Not permited
<i><b>var cannot use with multiple variable declarators</b></i>
<b>var</b> <b>x=69, y=9.6; //Error, Implicitly-typed local variables cannot have </b>
multiple declarators
<i>Declarator implicitly typed local variables must include a </i>
<i>local-variable-initializer</i>
<b>var</b> <b>x; //Error, no initializer to infer type from</b>
<i>The local-variable-initializer must be an expression</i>
<i>The initializer expression must have a compile-time type</i>
<b>Microsoft</b>
int defaultValue = 12345678;
<b>long value = defaultValue;</b>
int smallerValue = (int) value;
public class EntryPoint
{
static void Main()
{
int employeeID = 303;
object boxedID = employeeID;
employeeID = 404;
<b>int unboxedID = (int) boxedID;</b>
System.Console.WriteLine( employeeID.ToString()
System.Console.WriteLine( unboxedID.ToString() );
}
Permit the decimal, integer, literal to be converted to any enum
1. long x;
2. int y = 25;
<b>Microsoft</b>
From any reference type to object.
From any class type D to any class type B, provided D is inherited from
B.
From any class type A to interface type I, provided A implements I.
From any interface type I2 to any other interface type I1, provided I2
inherits I1.
From any array type to System.Array.
From any array type A with element type a to an array type B with
element type b provided A & B differ only in element type (but the same
number of elements) and both a and b are reference types and an
implicit reference conversion exists between a & b.
From any delegate type to System.Delegate type.
From any array type or delegate type to System.ICloneable.
From null type to any reference type.
Conversion of any value type to object type
1. int x = 10;
<b>Microsoft</b>
From sbyte, byte, short, ushort, int, uint, long, ulong, char, float,
double or decimal to any enum type.
From any enum type to sbyte, byte, short, ushort, int, uint, long,
ulong, char, float, double or decimal.
From any enum type to any other enum type
<b>36</b>
From object to any reference type.
From any class type B to any class type D, provided B is the
From any class type A to any interface type I, provided S is not
sealed and do not implement I.
From any interface type I to any class type A, provided A is not
sealed and implement I.
<b>Microsoft</b>
is used to perform conversions between compatible reference
types
The as operator is like a cast operation. However, if the
conversion is not possible, as returns null instead of raising an
exception
Checks if an object is compatible with a given type
An is expression evaluates to true if the provided expression is
non-null, and the provided object can be cast to the provided
type without causing an exception to be thrown
<b>The is operator only considers reference conversions, boxing </b>
conversions, and unboxing conversions
<b>Microsoft</b>
1. public class List
2. {
3. private object[] elements;
4. private int count;
5.
6. public void Add(object element) {
7. if (count == elements.Length) Resize(count*2);
8. elements[count++] = element;
9. }
10.
11. public object this[int index] {
12. get { return elements[index]; }
13. set { elements[index] = value; }
14. }
15.
16. public int Count {
17. get { return count; }
18. }
19. }
1. public class List<ItemType>
2. {
3. private ItemType[] elements;
4. private int count;
5.
6. public void Add(ItemType element) {
7. if (count == elements.Length) Resize(count*2);
8. elements[count++] = element;
9. }
10.
11. public ItemType this[int index] {
12. get { return elements[index]; }
13. set { elements[index] = value; }
14. }
15.
16. public int Count {
17. get { return count; }
18. }
19. }
<b>40</b>
1. List intList = new List();
2.
3. intList.Add(1);
4. intList.Add(2);
5. intList.Add("Three");
6.
7. int i = (int)intList[0];
1. List intList = new List();
2.
3. intList.Add(1); // Argument is boxed
4. intList.Add(2); // Argument is boxed
5. intList.Add("Three"); // Should be an error
6.
7. int i = (int)intList[0]; // Cast required
1. List<int> intList = new List<int>();
2.
3. intList.Add(1); // No boxing
4. intList.Add(2); // No boxing
5. intList.Add("Three"); // Compile-time error
6.
Type checking, no boxing, no downcasts
Reduced code bloat (typed collections)
Instantiated at run-time, not compile-time
Checked at declaration, not instantiation
Work for both reference and value types
<b>Microsoft</b>
Class, struct, interface and delegate
One base class, multiple interfaces, new()
Class, struct, interface, and delegate types
class Dictionary<KeyType, ValueType> {...}
struct Pair<FirstType, SecondType> {...}
interface IComparer<T> {...}
delegate ResType Func<ArgType, ResType>(ArgType
arg);
Dictionary<string, Customer>
customerLookupTable;
<b>Microsoft</b>
1. class Array
2. {
3. public static T[] Create<T>(int size) {
4. return new T[size];
5. }
6.
7. public static void Sort<T>(T[] array) {
8. ...
9. }
10. }
1. string[] names = Array.Create<string>(3);
2. names[0] = "Jones";
3. names[1] = "Anderson";
4. names[2] = "Williams";
5. Array.Sort(names);
Class, struct, interface, and delegate types
Methods
1. interface IComparable{int CompareTo(object obj);}
2.
3. class Dictionary<K, V>
4. {
5. public void Add(K key, V value) {
6. ...
7. switch (((IComparable)key).CompareTo(x)) {
8. ...
9. }
10. }
1. interface IComparable{int CompareTo(object obj);}
2. class Dictionary<K, V> where K: IComparable
3. {
4. public void Add(K key, V value) {
5. ...
6. switch (key.CompareTo(x)) {
7. ...
8. }
9. }
10. }
1. interface IComparable<T> {int CompareTo(T obj);}
2.
3. class Dictionary<K, V>: IDictionary<K, V> where
4. K: IComparable<K>,
5. V: IKeyProvider<K>,
6. V: IPersistable,
7. V: new()
8. {
9. ...
10. }
One base class, multiple interfaces, new()
<b>Microsoft</b>
<b>Microsoft</b>
Permit the use of types in a namespace, such that, you do not
have to qualify the use of a type in that namespace (a using
directive).
Console is a class of
namespace System.
<b>Microsoft</b>
<b>50</b>
1. namespace N1.N2
2. {
3. class A {}
4. }
5. namespace N3
6. {
7. using A = N1.N2.A;
8. class B: A {}
<b>Fundamentals</b>
System System.IO
System.AddIn System.Linq
System.Collections System.Reflection
System.ComponentModel System.Resources
System.Configuration System.Runtime
System.Diagnostics System.Security
<b>Microsoft</b>
Windows Presentation Foundation
System.Windows
Windows Forms
System.Drawing
System.Media
System.Windows.Forms
ASP.NET
System.Web
Communications and Workflow
System.Messaging
System.Net
System.Net.Sockets
System.ServiceModel
System.Web.Services
System.Workflow
DATA, XML and LINQ
<b>Microsoft</b>
<b>Microsoft</b>
<i><b>condition is a relational or logical expression.</b></i>
<i><b>statement(s)_1 is a statement (or a block of statements) that is </b></i>
<i>executed if the condition is true.</i>
<i><b>statement(s)_2 is a statement (or a block of statements) that is </b></i>
<i>executed if the condition is false</i>
<b>56</b>
1. if (salary > 2000)
2. Console.Write("Salary is greater than 2k");
1. if (salary > 2000)
2. Console.Write("Salary is greater than 2k");
<i>// The original result</i>
3. else
<b>Microsoft</b>
<b>switch (expression)</b>
<b>{</b>
<b>case constant-1: </b> <b>statement(s);</b>
<b>jump-statement</b>
<b>case constant-2: statement(s);</b>
<b>jump-statement</b>
<b>case constant-3:</b>
<b>...</b>
<b>[default: statement(s);</b>
<b>jump-statement]</b>
statement(s) is a
statement or
block of
statements that is
executed if the
corresponding
condition is
evaluated true
jump-statement is
a branching
statement to
transfer control
outside the specific
case, such as
break or goto
(explained later)
default deals
with all the
other cases
<b>58</b>
1. using System;
2. class Switch
3. {
4. static void main()
5. {
6. int n = 2;
7. switch (n)
8. {
9. case 1: Console.WriteLine("n=1");
10. break;
11. default: Console.WriteLine("n=2");
12. break;
13. }
14. }
<b>Microsoft</b>
<b>60</b>
<b>Microsoft</b>
<b>62</b>
terminates the closest enclosing loop or switch statement in
which it appears
<b>goto</b> <b>label;</b>
is not recommended because it corrupts the program structure
<b>goto case</b> expression; <b>goto default</b>; (in case struct)
<b>Microsoft</b>
terminates execution of the method in which it appears and
returns control to the calling method
is used to signal the occurrence of an anomalous situation
(exception) during the program execution
Usually is used with try-catch or try-finally statements