C#: Data Typer

  • View
    28

  • Download
    0

Embed Size (px)

DESCRIPTION

C#: Data Typer. Indhold:. - PowerPoint PPT Presentation

Text of C#: Data Typer

C#: Data Typer

C#: Data Typer3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel1Indhold:.NET is designed around the CTS, or Common Type System. The CTS is what allows assemblies, written in different languages, to work together. To ensure interoperability across languages, Microsoft has also defined the CLS, or Common Language Specification, a subset of the CTS that all languages support. Otherwise, the types in C# are what you would expect from a modern OOPL

The Common Type SystemValue vs. reference typerArraysNamespaces3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel2The Common Type System 1. delThe Common Type System (CTS)CTS er baseret p et hierarki af klasser defineret i FCLalle typer arver fra Object (undtagen interface typer)

3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel4Recall that FCL = Framework Class LibraryThe Common Language Specification (CLS)Ikke alle sprog understtter alle CTS typer og egenskaberC# understtter unsigned integer, VB.NET gr ikkeC# er case sensitiv, VB.NET er ikkeC# understtter pointere (i unsafe mode), VB.NET gr ikkeC# understtter operator overloading, VB.NET gr ikke

CLS var ment til at fremme forbindelsen mellem kode skrevet i forskellige sprogDen overvejende del af klasserne i FCL er i overensstemmelse med CLS

Mapping C# til CTSLanguage keywords map to common CTS classes:KeywordDescriptionSpecial format for literalsboolBooleantrue falsechar16 bit Unicode character'A' '\x0041' '\u0041'sbyte8 bit signed integernonebyte8 bit unsigned integernoneshort16 bit signed integernoneushort16 bit unsigned integernoneint32 bit signed integernoneuint32 bit unsigned integerU suffixlong64 bit signed integerL or l suffixulong64 bit unsigned integerU/u and L/l suffixfloat32 bit floating pointF or f suffixdouble64 bit floating pointno suffixdecimal128 bit high precisionM or m suffixstringcharacter sequence"hello", @"C:\dir\file.txt"EksempelEt eksempel p brug af typer i C#Variable skal erklres (compiler)Variable skal initialiseres (compiler)public class App{ public static void Main() { int width, height; width = 2; height = 4;

int area = width * height;

int x; int y = x * 2; ... }}ErklringErklring + initialieringFejl, x er ikke init.Type konversionImplicit type konversion:fra mindre til strre typeEllers er der brug for typecast eller explicit konversiontypecast syntaksen er typen i parentesKonversion baseret p System.Convert klassen

int i = 5;double d = 3.2;string s = "496";

d = i;

i = (int) d;

i = System.Convert.ToInt32(s);implicit konversiontypecast ndvendigKonversion ndvendigValue vs. reference typerPart 2Value vs. reference typerI C# er 2 kategorier af data typerValue typer:variablen reprsenterer en vrdi ("bits")

Reference typer:variablen reprsenterer en reference til et objektaktuelle data er indeholdt i objektet

int i;i = 10;10string s;s = "calico"; "calico"Hvordan ved du hvad der er hvad?Lr det udenad!Men ellers er det ikke s svrt:primitive typer som bool, int og double er valuesresten er reference typer

int i;string s;Customer c1, c2;

i = 23;s = "a message";c1 = null;c2 = new Customer();Boxing og UnboxingC# konverterer vrdi objekt, nr der er behovvrdi ==> objekt kaldes "boxing"objekt ==> vrdi kaldes "unboxing"int i, j;object obj;string s;

i = 32;obj = i; // boxed copy!i = 19;j = (int) obj; // unboxed!

s = j.ToString(); // boxed!s = 99.ToString(); // boxed!3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel12A nice change from Java, where programmer must convert between value and reference types.On the other hand, boxing can lead to subtle program errors since copies are madeBrugerdefinerede reference typer(Abstrakte datatyper)Klasser!for eksempel en kundeklassepublic class Customer{ public string name; // fields public int id;

public Customer(string name, int id) // constructor { this.name = name; this.id = id; }

public override string ToString() // method { return "Customer: " + this.name; }}Anvendelse af reference typer (klasser) Oprettelse, tildeling, og sammenligning:Customer c1, c2, c3;string s1, s2;

c1 = new Customer("joe hummel", 36259);c2 = new Customer("marybeth lore", 55298);c3 = null; // c3 references no object

c3 = c1; // c3 now references same obj as c1

if (c1 == null) ... // do I ref an object? if (c1 == c2) ... // compares references if (c1.Equals(c2)) ... // compares objects

if (s1 == s2) ... // exception: == overloaded to // compare string dataDefinering af Lig medKlasser br omdefinere Equalspublic class Customer{ . . .

public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // definitely not equal

other = (Customer) obj; // typecast to access return this.id == other.id; // equal if same id... }

3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel15When we override Equals, compiler will warn us to also override GetHashCode. In general, override GetHashCode to compute hash code based on field(s) used for equality test.Example: here's GetHashCode for Customer class above:public override int GetHashCode(){ return this.id.GetHashCode();}ArraysPart 3ArraysArrays er reference typerbaseret p Array klassen i FCLoprettes med new0-baseret indekseringTildelt default vrdier (0 for numerisk, null for references, etc.)int[] a;a = new int[5];

a[0] = 17;a[1] = 32;int x = a[0] + a[1] + a[4];

int l = a.Length;Tilg elementOpretAntal elementerMulti-dimensionelle arraysC# understtter arrays som et enkelt objekt ELLER som array af arraysnedenstende implementer et 2D array med forskellig lngde (Jagged) Customer[,] twoD;int[][] jagged2D;

// 2D array as single objecttwoD = new Customer[10, 100];twoD[0, 0] = new Customer();twoD[9, 99] = new Customer();

// 2D array as array of arraysjagged2D = new int[10][];jagged2D[0] = new int[10];jagged2D[1] = new int[20];jagged2D[9] = new int[100];

jagged2D[0][0] = 1;jagged2D[9][99] = 100;Samme lngdeForskellig lngdeNamespacesPart 4NamespacesNamespaces er beregnet til at organisere klasseset namespace N er et set af klasser i Ns scopenamespaces er ofte indlejredenamespace Workshop{ public class Customer { . . . }

public class Product { . . . }}//namespace Workshop.Customer

EksempelFramework Class Library (FCL) indeholder flere tusind klasserhvordan er de organiserede?hvordan undgs navnsammenfald?med FCLindenfor FCL

FCL namespacesFCL verste namespace er "System"FCL teknologier er indlejret i SystemNamespacePurposeAssemblySystemCore classes, typesmscorlib.dllSystem.CollectionsData structuresmscorlib.dllSystem.DataDatabase accessSystem.Data.dllSystem.Windows.FormsGUISystem.Windows.Forms.dllSystem.XMLXML processingSystem.Xml.dll3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel22Note that multiple namespaces can map to the same assemblyThus:namespaces are an organizational mechanismassemblies are an implementation / packaging mechanism

OpsummeringCTS er det flles type systemsamme type system for alle sprogtyperne er implementeret med klasser i FCLSimple datatyper er call by value, klasser er call by referenceCLS er den flles sprog specifikationtyper som med sikkerhed fungerer p tvrs af sprog

Pas p med at sammenblande namespaces med assembliesnamespaces hjlper med organisationassemblies refererer til implementation / packaging3. Data TypesJanuary 2003Denmark .NET Workshop 2003 Joe Hummel23