C#: Udtryk og metoder
Indhold “With regards to programming statements and methods, C# offers what you would come to expect from a modern OOPL…” Udtryk Metoder
Part 1 Udtryk…
Udtryk i C# C# har standard udtrykene… Værditildeling Subrutiner og funktionskald Betingelser if, switch Iteration for, while, do-while Control Flow return, break, continue, goto
Eksempler x = obj.foo(); if (x > 0 && x < 10) count++; else if (x == -1)... else {... } while (x > 0) {... x--; } for (int k = 0; k < 10; k++) {... }
Andre udtryk C# har også… iteration gennem en datastruktur via foreach namespace importering via using
foreach Specialiceret foreach løkke til sweep gennem f.eks array reducerer risiko for indekserings fejl Giver read only tilgang int[] data = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int x in data) { sum += x; } foreach typevaluecollection
using using direktiv giver adgang til klasser i et namespace uden at skulle angive det hver gang // before Workshop.Customer c; c = new Workshop.Customer("joe hummel", 94652); //after using Workshop; Customer c; c = new Customer("joe hummel", 94652); namespace Workshop { public class Customer {. } public class Product {. }
Et eksempel using direktiv(er) angives i toppen af filen /* main.cs */ using System; using Workshop; public class App { public static void Main() { Customer c; c = new Customer("joe hummel", 94652); Console.WriteLine( c.ToString() ); } namespace Workshop { public class Customer {. } public class Product {. }
Part 2 Metoder…
Typer af methoder Klasser kan indeholde 2 typer af methoder: instance static Instance methoder forudsætter instancering af et objekt Static methoder er globale og kræver kun klassenavnet
Eksempel Array klassen i FCL fully-qualified name is System.Array namespace System { public class Array { public int GetLength(int dimension) {... } public static void Sort(Array a) {... }. } instance metode (static ikke angivet) static metode (static angivet)
Metodekald Metodekald i Array klassen: /* main.cs */ using System; public class App { public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data); for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); }
Andre nyttige static metoder Et program til addere 2 heltal og udskrive summen: using System; public class Calculator { public static void Main() { string input, output; int a, b, sum; Console.Write("Enter first integer: "); input = Console.ReadLine(); a = Convert.ToInt32(input); Console.Write("Enter second integer: "); input = Console.ReadLine(); b = Convert.ToInt32(input); sum = a + b; output = String.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine(output); }
Opsummering Standardudtryk, og et par ikke-standard assignment, if, for, while, foreach, using To typer of metoder instance metoder kræver et objekt static metoder er globale og kræver kun en klasse