Professional Documents
Culture Documents
Orhan R Bakalli
Futja e kuadrit. NET Krahasimi C # pr C + + dhe Java T'ia Fillohet Llojet ndryshueshme vargjeve operatort Kontrolli Flow Klasat futur, strukturave dhe hapsira Deklarata Class Metodat Futja Polymorphism (Metodat e trashguara) Konstante, fusha, Prona dhe Indexers Delegatt dhe Ngjarje prjashtime Dokumentacioni Kodi
C# Tutorial
C#
Jo t gjitha gjuht e mbshtetur t prshtatet trsisht me kujdes n kuadrin. NET, por nj gjuh q sht e garantuar pr t prshtaten n mnyr t prkryer sht C #. C # (C Sharp), nj pasues t C + +, sht liruar n lidhje me kuadrin. NET. C dizajn Qllimet msgstr me: Jet t rehatshme pr C + + programues Fit pastr n. Runtime NET Gjuhsh e prbashkta CLR) Thjeshtoj C + modelin + E T siguroj sasi t drejtn e fleksibilitetit Komponent-centric mbshtetje t zhvillimitUndo edits
To compile the program on Mono, use the command: mcs HelloWorld.cs (csc HelloWorld.cs in .NET framework SDK) To run the program on Mono: mono HelloWorld.exe
Variable Types
C # sht nj lloj i sigurt-gjuha. Variablat jan deklaruar si t nj lloji t veant, dhe secili variabl sht e detyruar t mbaj vetm vlerat e llojit t saj t deklaruar. Variablat mund t mbaj as lloje vler ose llojet e referencs, apo ato mund t jen pointers. Nj variabl e llojeve me vler drejtprdrejt prmban vetm nj objekt me vler. Nj variabl e tipit reference direkt prmban nj referenc n nj objekt. Nj tjetr shum t ndryshueshme t prmbaj nj referenc pr t njjtin objekt. sht e mundur n C # pr t prcaktuar llojet e tuaja me vler duke deklaruar enumerations ose structs.
double
decimal char bool
System.Double
System.Decimal System.Char System.Boolean
Yes
Yes N/A N/A
8
12 2 1/2
Value Types
Llojet Vlera: int x = 10; Llojet e referencs: llojet e reja t referencs mund t prcaktohet duke prdorur 'klass', 'Te ndrfaqe', dhe '' t deleguar deklaratat objekt. Objekti x = objekt i ri (); x.myValue = 10; Ikni sekuenca dhe strings fjal pr fjal string a = "\" Hello World \ nHow jeni \ ""; Boks: C # ju lejon t konvertohet do lloj vler t nj lloji prkats referimi, dhe pr t kthyer rezultate s Gallery Boxed 'Tipi prsri. int i = 123; kuti objekt = i; if (kutia sht int) {Console.Write ("Kutia prmban nj int");} / / kjo linj sht e shtypurUndo edits
Pointers
Nj tregues sht nj ndryshore q mban adresn e kujtess s nj lloji tjetr. N C #, pointers mund t deklarohet pr t mbajtur adresat e memories t llojeve t vler. Pointers jan deklaruar n mnyr implicite, duke prdorur simbol dereferencer shtypur *.Operatori & kthen kujtess adresn e vete prefikset ndryshueshme. Shembull: Cila sht vlera e un? int i = 5; int * p; p = &i; * p = 10;Prdorimi i pointers sht i kufizuar pr kodin i cili sht shnuar si i pasigurt (hyrje kujtess).Undo edits
Pr t adresuar problemin e grumbullimit t mbeturinave, mund t deklaroj nj tregues brenda nj shprehje t caktuar. do lloje t vlers s deklaruar brenda kodit t pasigurt jan fikse automatikisht, dhe do t gjeneroj prpilojn me koh gabime n qoft se prdoren brenda shprehjeve fikse. E njjta gj nuk sht e vrtet pr lloje t referencs. Edhe pse zakonisht pointers mund t prdoren vetm me lloje t vler, nj prjashtim nga kjo prfshin vargjeve. Nj tregues mund t deklarohet n lidhje me nj grup, si n vijim: int [] = {a 4, 5}; int * b = a; far ndodh n kt rast sht se vendndodhja e kujtess mban b sht vend i llojit t par t mbajtur nga nj.
Pointers
Arrays
Single-dimensional arrays have a single dimension
int[] i = new int[100];
A jagged arrays is a multidimensional array that has the irregular dimensions sizes.
int[][] jag = new int[2][]; jag[0] = new int [4]; jag[1] = new int [6]; int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};
Enumerations
Nj regjistrimit sht nj lloj i veant i llojit t vlers s kufizuar n nj grup t kufizuar dhe t pandryshueshme t vlerave numerike. Kur ne t prcaktoj nj numrimit q ne ofrojm literals t cilat jan prdorur m pas si kosntanta pr vlerat e tyre prkatse.Kodi i mposhtm tregon nj shembull t till nj prkufizim: DITT publike enum {hn, e mart, e mrkur, e enjte, e premte, e shtun, e diel}; enum byteEnum: bajt {A, B}; N vend t ksaj, vlerat numerike jan ngritur n prputhje me kto dy rregulla: Pr literal i par: nse ajo sht e unassigned, pr t prcaktuar vlern e saj n 0. Pr do literal tjetr: nse ajo sht e unassigned, pastaj vendoset vlern e saj n nj m t madhe se vlera e literal msiprm.
Enumerations
using System; public class EnumTest { public enum DAYS: byte {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; public static void Main() { Array dayArray = Enum.GetValues(typeof(EnumTest.DAYS)); foreach (DAYS day in dayArray) Console.WriteLine("Number {1} of EnumTest.DAYS is {0}", day, day.ToString("d")); } }
Enumerations
is equivalent to:
Console.WriteLine(String.Format("Number {1} of EnumTest.DAYS is {0}", day, day.ToString("d")));
And what the String.Format method does is to take textual representations of the objects it is passed as parameters, and slots them into the appropriate places within the format string it is passed. So this line of code is basically equivalent to:
Console.WriteLine("Number " + day.ToString("d").ToString() + " of EnumTest.DAYS is " + day.ToString());
The ToString method can take a single IFormatProvider parameter which indicates how the string conversion should be conducted. Values for this parameter can include things like g, d, x, f, etc.
Operators
C# has a number of standard operators, taken from C, C++ and Java. Most of these should be quite familiar to programmers. To overload an operator in a class, one defines a method using the operator keyword. For instance, the following code overloads the equality operator.
public static bool operator == (Value a, Value b) {
Where an operator is one of a logical pair, both operators should be overwritten if any one is.
Loop Statements
while loops while (expression) statement[s] do-while loops do statement[s] while (expression) for loops for (statement1; expression; statement2) statement[s]3 foreach loops foreach (variable1 in variable2) statement[s]
int[] a = new int[]{1,2,3}; foreach (int b in a) System.Console.WriteLine(b);
Namespaces
Namespaces can be thought of as collections of classes; they provide unique identifiers for types by placing them in an hierarchical structure. To use the System.Security.Cryptography.AsymmetricAlgorithm class, specify it in the following statement: using System.Security.Cryptography; An alias for the namespace can be specified as using myAlias = System.Security.Cryptography; For instance, the following code states that the class Adder is in the namespace fred.math.
namespace fred { namespace math { public class Adder { // insert code here } } }
Class Declaration
Class declarations can have up to four different parts, surrounding the class keyword:
attributes class-modifiers class class-base class-body
The class-body element specifies type members. The following is an example of a class declaration:
public class Shape { // class-body }
Attributes can be posted at the front of a class declaration. These comprise user-defined meta-data about the class; information which can be brought out at runtime.
Class Declaration
Ka shtat t ndryshme - optional - modifiers klass. Katr nga kto - publik, t brendshm, t mbrojtur, dhe private - jan prdorur pr t prcaktoj nivelet e aksesit t llojeve t prcaktuara nga klasat.Fjalen publik identifikon nj lloj si plotsisht t arritshme pr t gjitha llojet e tjera. Nse nj klas sht deklaruar si t brendshme, tip ajo definon sht i arritshm vetm pr llojeve brenda kuvendit njjtin nj vet-prmbante 'njsi e paketimit' kodi prmban, metadata etj.) Nse nj klas sht shpallur e mbrojtur, llojin e saj sht e arritshme nga nj lloj q prmbajn dhe do lloji q trashgon nga ky lloj prmban. Kur nj klas sht deklaruar si private, qasja n llojin ajo definon sht i kufizuar n nj lloj q prmban vetm.
Class Declaration
Lejet e lejuara nga brendshme t mbrojtura jan ato t lejuara nga niveli i mbrojtur plus ato t lejuara nga niveli i brendshm.Fjalen e re mund t prdoret pr klasat e mbivendosur. Nj klas deklarohen si abstrakte nuk mund vet t instanced - ajo sht projektuar vetm pr t qen nj klas baz pr trashgim. Nj klas e shpallur si t mbyllur nuk mund t trashgohet nga.Undo edits
Class Declaration
Baza klas pjes e deklarats klass specifikon emrin e klass dhe t gjitha klasa q ai trashgon nga.Linja m posht deklaron nj klas publik t quajtur DrawingRectangle q trashgon nga drejtkndsh klass baz dhe vizatim ndrfaqes: DrawingRectangle publik klas: Rectangle, Vizatim Interfaces jan deklaruar n t njjtn mnyr si klasa standarde, prve se ata prdorin ndrfaqe fjalen n vend t klass fjalen. Pr shembull: Vizatim publik ndrfaqe
Methods
Metodat jan operacione q lidhen me llojet. int shuma = Arithmetic.addTwoIntegers (4, 7); Nj deklarat e metod, t specifikuara n nj deklarat t klass, prbn nj metod kok-dhe nj metodtrup.Metoda e-kreu sht i prbr nga elementet e mposhtme (kllapa katrore fus ato t cilat jan opsionale). [atribute] [metod t modifiers] kthimit-lloj metoda-name ([formal-parametr-list]) Atributet Metoda t punoj n nj mnyr t ngjashme me ato t klasave.
Methods
Ka dhjet modifiers metod q mund t prdoren. Katr nga kto jan modifiers qasje q mund t prdoren n deklaratat e klass. Kto pun katr analoge pr mnyrn se si ata punojn n deklaratat e klass. T tjert jan si m posht: Abstract: Nj metod pa specifikuar trupin e saj. Metoda t tilla jan vet quajtur abstrakte. Nj klas prmban nj metod abstrakt ai nuk mund t instantiated.Modifier statike deklaron nj metod t jet nj metod klas (nj metod q mund t prdoret pa nj shembull). Hapsira t meta Paketat n Java) mund t mendohet si koleksionet e klasave, ata japin identifikues unik pr lloje duke i vendosur ato n nj struktur hierarkike.Undo edits
Delegates
using System; using System.Threading; public class Ticker { private int i = 0; public void Tick(Object obj) { Console.WriteLine("tick " + ++i); } } public class DelegateExample { static void Main(string[] args) { Ticker ticker = new Ticker(); TimerCallback tickDelegate = new TimerCallback(ticker.Tick); new Timer(tickDelegate, null, 0, 500); Thread.Sleep(5000); // The main thread will now sleep for 5 seconds: } }
Input/Output
using System; using System.IO; class DisplayFile { static void Main(string[] args) { StreamReader r = new StreamReader(args[0]); string line; Console.Write("Out File Name: "); StreamWriter w = new StreamWriter(Console.ReadLine()); while((line = r.ReadLine()) != null) { Console.WriteLine(line); w.WriteLine(line); } r.Close(); w.Close(); } }
Exceptions
Trajtimin prjashtim n C #, Java dhe sht mjaft e ngjashme. Megjithat, C # vijon C + + pr t lejuar q autori t injoroj m shum nga prjashtimet q mund t jet hedhur (nj prjashtim i cili sht hedhur, por nuk kapet do t ndal programin dhe mund t hedhin nj kuti t dialogut). Pr t kapur nj lloji t veant prjashtim n nj pjes t kodit, ju duhet q s pari t prfundoj at n nj bllok provoni dhe pastaj specifikoni nj bllok catch prputhen at lloj t prjashtim. Kur nj prjashtim ndodh n kodin brenda bllokut t provoni, ekzekutimi Kodi lviz deri n fund t kutis s provoni dhe shikon pr nj mbajts prjashtim t prshtatshme.
Exceptions
For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:
try { res = (num / 0); catch (System.DivideByZeroException e) { Console.WriteLine("Error: an attempt to divide by zero"); } }
You can specify multiple catch blocks (following each other), to catch different types of exception. A program can throw exceptions - including customized exceptions.
Exceptions
using System; public class ExceptionDemo { public static void Main () { try { getException(); } catch (Exception e) { Console.WriteLine("We got an exception"); } finally { Console.WriteLine("The end of the program"); } } public static void getException() { throw new Exception(); } }
Code Documentation
# C compiler mbshtet krijimin automatik t dokumentacionit t klass. Ku funksionaliteti ekuivalent pr Java prodhon HTML, dokumentuesi # C prodhon XML. Kjo do t thot se C # dokumentacioni nuk sht aq e menjher i gatshm pr t prdorur si dokumentacionit Java. Megjithat, kjo nuk lejon q t ket aplikime t ndryshme t cilat mund t importojn dhe t prdorin dokumentacionin C # n mnyra t ndryshme. (Shnim: duke prdorur Visual Studio ju gjithashtu mund t krijoj dokumentacionin HTML, por ne nuk do t mbulojn kt ktu). T dokumentoj do element n nj skenar C #, ju paraprijn elementin me elemente XML. Secili prej linjave t prbr kt kod dokumentar duhet t shnohet off si komente duke prdorur treguesin e mposhtme t veant Komenti (ju mund ta krahasoni kt me treguesit Komento standarde).
Code Documentation
Kodi vijim jep nj shembull se si mund t japin informacion rishikim pr nj klas. / / / <summary> / / / Klasa myClass prfaqson nj klas arbitrar / / / </ Prmbledhje> myClass publik klas Gjenerimi C Dokumentimi msgstr Ju thoni prpilues pr t prodhuar dokumentacionin kur hartimin duke iu lutur me t kaloni: / doc: fotografi N kt kaloni, fotografi paraqet emrin e skedarit q doni t dokumentacionit me shkrim. Si dokumentacion sht gjeneruar n formatin XML, dosja duhet t ket extension. XML. Kshtu, pr shembull, pr t prodhuar dokumentacionin pr nj program n sys.cs dosjes n nj skedar t quajtur my.xml, ne do t prdorim komandn: KSHC sys.cs / doc: my.xml