charles university in prague jezek faculty of mathematics and physics c# language &.net platform...

Post on 14-Dec-2015

219 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CHARLES UNIVERSITY IN PRAGUE

http://d3s.mff.cuni.cz/~jezek

faculty of mathematics and physics

C# Language & .NET Platform

12th-13th Lecture

Pavel Ježekpavel.jezek@d3s.mff.cuni.cz

Some of the slides are based on University of Linz .NET presentations.© University of Linz, Institute for System Software, 2004

published under the Microsoft Curriculum License(http://www.msdnaa.net/curriculum/license_curriculum.aspx)

CLI Type SystemAll types

Reference types(allocated on

managed heap)

PointersValue types(allocated in-place

[with exceptions])

Classes(e.g. strings)

Interfaces Arrays Delegates

Simple types(Int32, Int64,

Double, Boolean, Char, …)

Nullables

EnumerationsStructures

User defined structures

CLI Type InheritanceSystem.Object(C# keyword: object)

user-defined classes(C# keyword: class)

delegates(C# keyword: delegate)

pointers(C#: Type *)

System.Delegate

System.MulticastDelegate

System.ValueType

System.Enum

System.Array

arrays(C#: Type[] or Type[,])

System.String(C# keyword: string)

interfaces(C# keyword: interface)

user-defined structures

(C# keyword: struct)

enumerations(C# keyword: enum)

System.Int32(C# keyword: int)

System.Int64(C# keyword: long)

System.Double(C# keyword: double)

System.Boolean(C# keyword: bool)

simple types

System.Nullable(C#: Type?)

Interfaces

Interface Constraints: Is It Correct?interface I1 {

void m();} interface I2 {

void m();} class B : I1, I2 {

public void m() {Console.WriteLine("B.m()");

}} class Y<T> where T : I1, I2 {

public static void m(T t) {t.m();

}} class Program {

static void Main(string[] args) {new B().m();Y<B>.m(new B());

}}

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

?}

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

public void m(int x) { Console.WriteLine("int m"); }

public void m(long x) { Console.WriteLine("long m"); }

public int m() { return -1; }

long I<long>.m() { return -2; }

}

class Program {

static void Main(string[] args) {

A a = new A();

a.m(0);

a.m(0L); // Same as a.m(0l);

((I<int>) a).m(0);

((I<long>) a).m(0);

Console.WriteLine(a.m());

Console.WriteLine(((I<long>) a).m());

}

}

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

public void m(int x) { Console.WriteLine("int m"); }

public void m(long x) { Console.WriteLine("long m"); }

public int m() { return -1; }

long I<long>.m() { return -2; }

}

class Program {

static void Main(string[] args) {

A a = new A();

a.m(0);

a.m(0L); // Same as a.m(0l);

((I<int>) a).m(0);

((I<long>) a).m(0);

Console.WriteLine(a.m());

Console.WriteLine(((I<long>) a).m());

}

}

Interfaces and Value Types

Covariance and Contravariance

Any Meaningful Application of the Type Below?

struct X<T> where T : class {

private T t;

public static implicit operator T(X<T> x) {

return x.t; 

}

public static implicit operator X<T>(T t) {

X<T> x;

x.t = t;

return x;

}

}

IDisposable

public interface IDisposable {void Dispose()

}

public class ObjectDisposedException : InvalidOperationException {}

Class System.Object

Topmost base class of all other classesclass Object {

protected object MemberwiseClone() {...}public Type GetType() {...}public virtual bool Equals (object o) {...}public virtual string ToString() {...}public virtual int GetHashCode() {...}public static bool ReferenceEquals(object objA, object objB);

}

IEqualityComparer<in T>

EqualityComparer<T>.Default: a default implementation of a IEqualityComparer<T> for type T

public interface IEqualityComparer<in T> {int GetHashCode(T obj);bool Equals(T x, T y);

}

Used by Dictionary<T> and HashSet<T> collections.

Class System.Object

Topmost base class of all other classesclass Object {

protected object MemberwiseClone() {...}public Type GetType() {...}public virtual bool Equals (object o) {...}public virtual string ToString() {...}public virtual int GetHashCode() {...}public static bool ReferenceEquals(object objA, object objB);

}

Sorting: IComparable and IComparer

IComparable is interface for types with order

classes implementing IComparable arevalues types like Int32, Double, DateTime, …class Enum as base class of all enumeration typesclass String

IComparer is interface for the realization of compare operators

public interface IComparer {int Compare(object x, object y); // <0 if x < y, 0 if x == y, >0 if x > y

}

public interface IComparer<in T> {int Compare(T x, T y); // <0 if x < y, 0 if x == y, >0 if x > y

}

public interface IComparable {int CompareTo(object obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj

}

public interface IComparable<in T> {int CompareTo(T obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj

}

Custom IComparer Implementation

Creation of table of strings:

string[][] Table = {new string[] {"John", "Dow", "programmer"},new string[] {"Bob", "Smith", "agent"},new string[] {"Jane", "Dow", "assistant"},new string[] {"Jack", "Sparrow", "manager"}

};

Printing the table:

foreach (string[] Row in Table) {Console.WriteLine(String.Join(", ", Row));

}

Custom IComparer Implementation (2)

Comparer for single table (array) column:

class ArrayComparer<T> : IComparer<T[]> where T : IComparable<T> {private int m_Index;

public ArrayComparer(int Index) {m_Index = Index;

}

public int Compare(T[] x, T[] y) {return x[m_Index].CompareTo(y[m_Index]);

}}

Printing the table:

Array.Sort(Employees, new ArrayComparer<string>(2));

foreach (string[] Row in Employees) {Console.WriteLine(String.Join(", ", Row));

}

Bob, Smith, agentJane, Dow, assistantJack, Sparrow, managerJohn, Dow, programmer

"BCL v2-friendly" Custom Classes 1/3

In order to cooperate smoothly with other BCL classesin the framework 2.0, custom classes should:

override ToString and GetHashCode

overload == and !=

implement ICloneable public interface ICloneable { object Clone(); }

class MyClass : ICloneable { public object Clone() { return MemberwiseClone(); } }

"BCL v2-friendly" Custom Classes 2/3

implement IComparable and IComparable<T> public interface IComparable { int CompareTo(object obj); // <0: this < obj, 0: this == obj, >0: this > obj }

public interface IComparable<T> { int CompareTo(T obj); // <0: this < obj, 0: this == obj, >0: this > obj }

class Fraction : IComparable, IComparable<Fraction> { int n, d;

public int CompareTo(object obj) { if (f == null) return 1; if (!(obj is Fraction)) throw new ArgumentException(“Must be of Fraction type.”, “obj”); return CompareTo((Fraction) obj); }

public int CompareTo(Fraction f) { if (f == null) return 1;

return n*f.d – f.n*d } }

"BCL v2-friendly" Custom Classes 3/3

override Equals(object) and implement IEquatable<T> public class Object { public virtual bool Equals(Object obj); … }

public interface IEquatable<T> { bool Equals(T other); }

class Fraction : IEquatable<Fraction> { // equal to class Fraction : object, IEquatable<Fraction> int n, d; public override bool Equals(object obj) { Fraction f = obj as Fraction; if (f == null) return false; return Equals(f); }

public bool Equals(Fraction f) { return f.n == n && f.d == d; } }

interface IEnumerator {object Current {get;}bool MoveNext();void Reset();

}

IEnumerable and IEnumerator (1)

Anything which is enumerable is represented by interface IEnumerable

IEnumerator realizes an iterator

Also generic versions IEnumerable<out T> and IEnumerator<out T>Enumerator should throw an InvalidOperationException on concurrent modification!

interface IEnumerable { IEnumerator GetEnumerator(); }

IEnumerable and IEnumerator

following statement:

foreach (ElementType element in collection) statement;

is translated into:

IEnumerator enumerator = ((IEnumerable) collection).GetEnumerator();try {

ElementType element;while (enumerator.MoveNext()) {

element = (ElementType) enumerator.Current;statement;

}} finally {

IDisposable disposable = enumerator as IDisposable;if (disposable != null) disposable.Dispose();

}

IEnumerable and IEnumerator (optimized)

following statement:

foreach (ElementType element in collection) statement;

is translated into:

var enumerator = collection.GetEnumerator();try {

ElementType element;while (enumerator.MoveNext()) {

element = (ElementType) enumerator.Current;statement;

}} finally {

IDisposable disposable = enumerator as IDisposable;if (disposable != null) disposable.Dispose();

}

Iterators so far

foreach loop can be applied to objects of classes which implement IEnumerable

class MyClass: IEnumerable<T> { ... public IEnumerator<T> GetEnumerator() { return new MyEnumerator(...); }

private class MyEnumerator: IEnumerator<string> { public string Current { get {...} } public bool MoveNext() {...} public void Reset() {...} }}

MyClass x = new MyClass();...foreach (string s in x) ...

complicated to implement!!

interface IEnumerable<T> { IEnumerator<T> GetEnumerator();}

Iterator Methods

class MyClass { string first = "first"; string second = "second"; string third = "third"; ... public IEnumerator<string> GetEnumerator() { yield return first; yield return second; yield return third; }}

Characteristics of an interator method

1. has the signaturepublic IEnumerator<T> GetEnumerator

2. statement body contains at leastone yield statement

MyClass x = new MyClass();...foreach (string s in x) Console.Write(s + " ");// prints "first second third "

1. returns a sequence of values

2. foreach loop traverses this sequence

How does an iterator method work?

Note• MyClass need not implement IEnumerable!

What Happens Behind the Scene?

public IEnumerator<int> GetEnumerator() { try { ... } finally { ... }}

returns an object of the following class

class _Enumerator1 : IEnumerator<int> { int Current { get {...} } bool MoveNext() {...} void Dispose() {...}}

foreach (int x in list) Console.WriteLine(x);

is translated into

IEnumerator<int> _e = list.GetEnumerator();try { while (_e.MoveNext()) Console.WriteLine(_e.Current);} finally { if (_e != null) _e.Dispose();}

MoveNext runs to the next yield statement

Dispose executes a possibly existingfinally block in the iterator method

Implementationclass Stack<T>: IEnumerable<T> {

... public IEnumerator<T> GetEnumerator() {

return new __Enumerator1(this);}

class __Enumerator1: IEnumerator<T>, IEnumerator { int __state; T __current; Stack<T> __this; int i;

... public bool MoveNext() {

switch (__state) { case 1: goto __state1; case 2: goto __state2; } i = __this.count - 1; __loop: if (i < 0) goto __state2; __current = __this.items[i]; __state = 1; return true; __state1: --i; goto __loop; __state2: __state = 2; return false; }}

}

class Stack<T>: IEnumerable<T> {T[] items;int count;

public void Push(T item) { } public T Pop() { }

public IEnumerator<T> GetEnumerator() { for (int i = count - 1; i >= 0; --i) {

yield return items[i]; }

}}

yield Statement

2 kinds

yield return expr; • yields a value for the foreach loop• may only occur in an iterator method• type of expr must be compatible with

- T (if IEnumerator<T>)- object (otherwise)

yield break; • terminates the iteration• may only occur in an iterator method

Specific Iterators

class MyList { int[] data = ...;

public IEnumerator<int> GetEnumerator() { for (int i = 0; i < data.Length; i++) yield return data[i]; }

}

Standard iterator

Specific iterator as a method• arbitrary name and parameter list• result type IEnumerable or IEnumerable<T>

public IEnumerable<int> Range(int from, int to) { if (to > data.Length) to = data.Length; for (int i = from; i < to; i++) yield return data[i];}

Specific iterator as a property• arbitrary name• result type IEnumerable or IEnumerable<T>

public IEnumerable<int> Downwards { get { for (int i = data.Length - 1; i >= 0; i--) yield return data[i]; }}

MyList list = new MyList();foreach (int x in list) Console.WriteLine(x);foreach (int x in list.Range(2, 7)) Console.WriteLine(x);foreach (int x in list.Downwards) Console.WriteLine(x);

How Specific Iterators are Compiled

public IEnumerable<int> Range(int from, int to) { if (to > data.Length) to = data.Length; for (int i = from; i < to; i++) yield return data[i];}

class _Enumerable : IEnumerable<int> { IEnumerator<int> GetEnumerator();}

class _Enumerator : IEnumerator<int> { int from, to; int Current { get {...} } bool MoveNext() {...} void Dispose() {..}}

returns an object of the following class

this returns an object of the following class

foreach (int x in list.Range(2, 7)) Console.WriteLine(x);

IEnumerator<int> _e = list.Range(2, 7).GetEnumerator();try { while (_e.MoveNext()) Console.WriteLine(_e.Current);} finally { if (_e != null) _e.Dispose();}

is translated into

top related