1、Quick C#Quick C#Learn C# in less than an hour. Discover the C# language constructs and features in a brief yet comprehensive way using code examples. This article is especially good if you know C+ and feel lazy about learning C#!IntroductionC# is a language with the features of C+, programming style
2、 like Java and rapid application model of BASIC. If you already know the C+ language, it will take you less than an hour to quickly go through the syntax of C#. Familiarity with Java will be a plus, as Java program structure, the concept of packages and garbage collection will definitely help you le
3、arn C# more quickly. So while discussing C# language constructs, I will assume, you know C+.This article discusses the C# language constructs and features using code examples, in a brief and comprehensive way, so that you just by having a glance at the code, can understand the concepts.Note: This ar
4、ticle is not for C# gurus. There must be some other beginners articles on C#, but this is yet another one.Following topics of C# language are discussed: Program structure Namespaces Data types Variables Operators and expressions Enumerations Statements Classes and structs Modifiers Properties Interf
5、aces Function parameters Arrays Indexers Boxing and unboxing Delegates Inheritance and polymorphismFollowing are not discussed: Things which are common in C+ and C#. Concepts like garbage collection, threading, file processing etc. Data type conversions Exception handling .NET libraryProgram structu
6、reLike C+, C# is case-sensitive. Semi colon (;) is the statement separator. Unlike C+, there are no separate declaration (header) and implementation (CPP) files in C#. All code (class declaration and implementation) is placed in one file with extensioncs.Have a look at this Hello world program in C#
7、.using System;namespace MyNameSpaceclass HelloWorld static void Main(string args) Console.WriteLine (Hello World); Everything in C# is packed into a class and classes in C# are packed into namespaces (just like files in a folder). Like C+, a main method is the entry point of your program. C+s main f
8、unction is calledmainwhereas C#s main function starts with capital M and is named asMain.No need to put a semi colon after a class block orstructdefinition. It was in C+, C# doesnt require that.NamespaceEvery class is packaged into a namespace. Namespaces are exactly the same concept as in C+, but i
9、n C# we use namespaces more frequently than in C+. You can access a class in a namespace using dot (.) qualifier.MyNameSpaceis the namespace in hello world program above.Now consider you want to access theHelloWorldclass from some other class in some other namespace.using System;namespace AnotherNam
10、eSpace class AnotherClass public void Func() Console.WriteLine (Hello World); Now from yourHelloWorldclass you can access it as:using System;using AnotherNameSpace; / you will add this using statementnamespace MyNameSpaceclass HelloWorld static void Main(string args) AnotherClass obj = new AnotherCl
11、ass(); obj.Func(); In .NET library,Systemis the top level namespace in which other namespaces exist. By default there exists a global namespace, so a class defined outside a namespace goes directly into this global namespace and hence you can access this class without any qualifier.You can also defi
12、ne nested namespaces.UsingThe#includedirective is replaced withusingkeyword, which is followed by a namespace name. Just asusingSystemas above.Systemis the base level namespace in which all other namespaces and classes are packed. The base class for all objects isObjectin theSystemnamespace.Variable
13、sVariables in C# are almost the same as in C+ except for these differences: Variables in C# (unlike C+), always need to be initialized before you access them, otherwise you will get compile time error. Hence, its impossible to access an un-initialized variable. You cant access a “dangling” pointer i
14、n C#. An expression that indexes an array beyond its bounds is also not accessible. There areno global variablesor functions in C# and the behavior of globals is achieved through static functions and static variables.Data typesAll types of C# are derived from a base classobject. There are two types
15、of data types: Basic/ built-in types User-defined typesFollowing is a table which lists built-in C# types:TypeBytesDescriptionbyte1unsigned bytesbyte1signed byteshort2signed shortushort2unsigned shortint4signed integeruint4unsigned integerlong8signed longulong8unsigned longfloat4floating point numbe
16、rdouble8double precision numberdecimal8fixed precision numberstringUnicode stringcharUnicode charbooltrue,falsebooleanNote: Type range in C# and C+ are different, example, long in C+ is 4 bytes, and in C# it is 8 bytes. Also theboolandstringtypes are different than those in C+.boolaccepts onlytruean
17、dfalseand not any integer.User defined types includes: Classes Structs InterfacesMemory allocation of the data types divides them into two types: Value types Reference typesValue typesValues types are those data types which are allocated in stack. They include: All basic or built-in types exceptstri
18、ngs Structs EnumtypesReference typesReference types are allocated on heap and are garbage collected when they are no longer being used. They are created usingnewoperator, and there is nodeleteoperator for these types unlike C+ where user has to explicitly delete the types created usingdeleteoperator
19、. In C#, they are automatically collected by garbage collector.Reference types include: Classes Interfaces Collection types likeArrays StringEnumerationEnumerations in C# are exactly like C+. Defined through a keywordenum.Example:enum Weekdays Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday,
20、FridayClasses and structsClasses andstructs are same as in C+, except the difference of their memory allocation. Objects of classes are allocated in heap, and are created usingnew, where asstructs are allocated in stack.Structs in C# are very light and fast data types. For heavy data types, you shou
21、ld create classes.Examples:struct Date int day; int month; int year; class Date int day; int month; int year; string weekday; string monthName; public int GetDay() return day; public int GetMonth() return month; public int GetYear() return year; public void SetDay(int Day) day = Day ; public void Se
22、tMonth(int Month) month = Month; public void SetYear(int Year) year = Year; public bool IsLeapYear() return (year/4 = 0); public void SetDate (int day, int month, int year) .PropertiesIf you are familiar with the object oriented way of C+, you must have an idea of properties. Properties in above exa
23、mple ofDateclass areday,monthandyearfor which in C+, you writeGetandSetmethods. C# provides a more convenient, simple and straight forward way of accessing properties.So above class can be written as:using System;class Date public int Day get return day; set day = value; int day; public int Month ge
24、t return month; set month = value; int month; public int Year get return year; set year = value; int year; public bool IsLeapYear(int year) return year%4= 0 ? true: false; public void SetDate (int day, int month, int year) this.day = day; this.month = month; this.year = year; Here is the way you wil
25、l get and set these properties:class User public static void Main() Date date = new Date(); date.Day = 27; date.Month = 6; date.Year = 2003; Console.WriteLine (Date: 0/1/2, date.Day, date.Month, date.Year); ModifiersYou must be aware ofpublic,privateandprotectedmodifiers that are commonly used in C+
26、. I will here discuss some new modifiers introduced by C#.readonlyreadonlymodifier is used only for the class data members. As the name indicates, thereadonlydata members can only be read, once they are written either by directly initializing them or assigning values to them in constructor. The diff
27、erence between thereadonlyandconstdata members is thatconstrequires you to initialize with the declaration, that is directly. See example code:class MyClass const int constInt = 100; /directly readonly int myInt = 5; /directly readonly int myInt2; public MyClass() myInt2 = 8; /Indirectly public Func
28、() myInt = 7; /Illegal Console.WriteLine(myInt2.ToString(); sealedsealedmodifier with a class dont let you derive any class from it. So you use thissealedkeyword for the classes which you dont want to be inherited from.sealed class CanNotbeTheParent int a = 5;unsafeYou can define an unsafe context i
29、n C# usingunsafemodifier. In unsafe context, you can write an unsafe code, example: C+ pointers etc. See the following code:public unsafe MyFunction( int * pInt, double* pDouble) int* pAnotherInt = new int; *pAnotherInt = 10; pInt = pAnotherInt; . *pDouble = 8.9; InterfacesIf you have an idea of COM
30、, you will immediately know what I am talking about. Aninterfaceis the abstract base class containing only the function signatures whose implementation is provided by the child class. In C#, you define such classes as interfaces using theinterfacekeyword. .NET is based on such interfaces. In C#, where you cant use multiple class inheritance, whi
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1