A concise introductory tutorial on learning C # in X minutes _java

Source: Internet
Author: User
Tags bitwise bitwise operators case statement data structures datetime define get hash static class

Copy Code code as follows:



Single-line comment to//start


/*


Multiline comments are like this.


*/


<summary>


XML document annotations


</summary>

Declaring the namespaces that are used by the application
Using System;
Using System.Collections.Generic;
Using System.Data.Entity;
Using System.dynamic;
Using System.Linq;
Using System.Linq.Expressions;
Using System.Net;
Using System.Threading.Tasks;
Using System.IO;

Defining scopes, organizing code into packages


Namespace Learning


{


Each. cs file needs to contain at least one class with the same file name


You may not do it, but it's not good.


public class Learncsharp


{


If you have used Java or C + + before, you can jump directly to the later "interesting features"


public static void Syntax ()


{


Print information using Console.WriteLine


Console.WriteLine ("Hello World");


Console.WriteLine (


"Integer:" + 10 +


"Double:" + 3.14 +


"Boolean:" + true);

Print with Console.Write without line-wrapping symbols
Console.Write ("Hello");
Console.Write ("World");

///////////////////////////////////////////////////
Types and variables
//
Define variables using <type> <name>
///////////////////////////////////////////////////

Sbyte-Signed 8-bit integer
( -128 <= sbyte <= 127)
sbyte foosbyte = 100;

Byte-unsigned 8-bit integer
(0 <= byte <= 255)
byte foobyte = 100;

Short-16-bit integer
Signed-( -32,768 <= short <= 32,767)
Unsigned-(0 <= ushort <= 65,535)
Short fooshort = 10000;
UShort Fooushort = 10000;

Integer-32-bit integer
int fooint = 1; ( -2,147,483,648 <= int <= 2,147,483,647)
UINT Foouint = 1; (0 <= UINT <= 4,294,967,295)

Long-64-bit integer
Long Foolong = 100000L; ( -9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
ULONG Fooulong = 100000L; (0 <= ulong <= 18,446,744,073,709,551,615)
number defaults to int or uint (depending on size)
Use L to indicate that the variable value type is long or ulong

Double-double-precision 64-bit IEEE 754 floating-point numbers
Double foodouble = 123.4; Precision: 15-16-bit

Float-single-precision 32-bit IEEE 754 floating-point numbers
float foofloat = 234.5f; Precision: 7-bit
Use F to indicate that the variable value type is float

Decimal-128-bits data type, higher precision than other floating-point types, for financial, financial
Decimal foodecimal = 150.3m;

Boolean value-True & False
bool Fooboolean = true; or false

Char-Single 16-bit Unicode character
Char Foochar = ' A ';

Strings-Unlike the previous basic type, the string is not a value, but a reference. This means that you can set the string to null.
string foostring = "\" escape\ "quotes and add \ n (new lines) and \ t (tabs)";
Console.WriteLine (foostring);

You can access each character of the string by index:
Char charfromstring = foostring[1]; => ' E '
String cannot be modified: foostring[1] = ' X ' is not workable.

Compare strings based on current locale settings, insensitive to capitalization
String.Compare (foostring, "X", stringcomparison.currentcultureignorecase);

String formatting based on sprintf
String foofs = String. Format ("Check check, {0} {1}, {0} {1:0.0}", 1, 2);

Date and format
DateTime foodate = DateTime.Now;
Console.WriteLine (Foodate.tostring ("hh:mm, dd MMM yyyy"));

Use the @ symbol to create a string that spans rows. Use "" to represent the
String bazstring = @ "Here ' s some stuff
On a new line! "Wow!" ", The masses cried";

Use const or read-only to define constants, constants in the compile-time calculus
const int Hours_i_work_per_week = 9001;

///////////////////////////////////////////////////
Data
///////////////////////////////////////////////////

Array-counts from 0, and you need to determine the length of the array when declaring the array.
The format of the declaration array is as follows:
<datatype>[] <var name> = new <datatype>[<array size>];
int[] Intarray = new INT[10];

Other ways to declare and initialize an array:
Int[] y = {9000, 1000, 1337};

           //Accessing elements of an array
             Console.WriteLine ("Intarray @ 0:" + intarray[0]);
           //array can be modified
             intarray[1] = 1;

           //list
            /lists are more common than arrays because the list is more flexible. The
           //Declaration list is formatted as follows:
            //list<datatype> <var name> = new list<datatype> ();
            list<int> intlist = new List<int > ();
            list<string> stringlist = new list< String> ();
            list<int> z = new List<int> {9000 , 1000, 1337}; Intialize
           /<> for generics-reference context

List has no default value, you must first add elements when accessing list elements
Intlist.add (1);
Console.WriteLine ("Intlist @ 0:" + intlist[0]);

Other data structures:
Stack/queue
Dictionary (Implementation of a hash table)
Hash collection
Read-only collection
Tuples (. Net 4+)

///////////////////////////////////////
Operator
///////////////////////////////////////
Console.WriteLine ("\n->operators");

int i1 = 1, i2 = 2; Abbreviated form of multiple declarations

Straightforward arithmetic.
Console.WriteLine (I1 + i2-i1 * 3/7); => 3

Take more
Console.WriteLine ("11%3 =" + (11% 3)); => 2

           //comparison operators
             Console.WriteLine ("3 = 2?" + (3 = 2)); => false
            Console.WriteLine ("3!= 2?" + 3 != 2)); => true
            Console.WriteLine ("3 > 2?" + ( 3 > 2)); => true
            Console.WriteLine ("3 < 2?" + ( 3 < 2)); => false
            Console.WriteLine ("2 <= 2?" + (2 <= 2)); => true
            Console.WriteLine ("2 >= 2?" + (2 >= 2)); => true

           /Bitwise operators
            /*
            ~        Anti-
            <<      move left (signed)
             >>      Move right (signed)
             &       and
             ^      -Bitwise XOR or
             |       or
             */

           /self-increase, self-reduction
             int i = 0;
            Console.WriteLine ("\n->inc/ Dec-rementation ");
            Console.WriteLine (i++);//i = 1. Post-Increase
            Console.WriteLine (++i); i = 2. Self-added
            Console.WriteLine (i--) in advance;//i = 1. Self-reduction after the event
            Console.WriteLine (i);//i = 0. Self-reduction in advance

///////////////////////////////////////
Control structure
///////////////////////////////////////
Console.WriteLine ("\n->control structures");

If statement similar to C


int j = 10;


if (j = = 10)


{


Console.WriteLine ("I Get Printed");


}


else if (J &gt; 10)


{


Console.WriteLine ("I don ' t");


}


Else


{


Console.WriteLine ("I also don ' t");


}

Three-dimensional expression
A simple If/else statement can be written as:
<condition>? <true>: <false>
String isTrue = (true)? ' True ': ' False ';

           //While loop
             int foowhile = 0;
            while (Foowhile < MB)
             {
                //Iterations 100 times, foowhile 0->99
                 foowhile++;
           }

           //Do While loop
             int foodowhile = 0;
            do
             {
                //Iterations 100 times, foodowhile 0->99
                 foodowhile++;
           } while (Foodowhile < MB);

           //for Loops
            //FOR circular Structure => for (< initial conditions >; < condition >; < >)
             for (int foofor = 0; foofor < foofor++)
   & nbsp;        {
                //Iterations 10 times, foofor 0->9
            }

           /foreach Loop
            //Foreach Loop structure => foreach (< iterator type > < iterator > in < enumerable architecture >) The
           //foreach loop applies to any implementation of the IEnumerable or The object of the IEnumerable.
The collection type (array, list, dictionary ...) under the            //. Net Framework. All of these interfaces are implemented.
           //The following code, ToCharArray () can be deleted, Because the string also implements the IEnumerable.
            foreach (char character in "Hello World"). ToCharArray ())
            {
    All characters in the             //iteration string
            }

Switch statement


switch applies to Byte, short, char, and int data types.


The same applies to enumerable types, including string classes,


And some classes that encapsulate the original values: Character, Byte, short, and integer.


int month = 3;


String monthstring;


Switch (month)


{


Case 1:


monthstring = "January";


Break


Case 2:


monthstring = "February";


Break


Case 3:


monthstring = "March";


Break


You can match multiple case statements at once


But you need to use break after adding a case statement


(Otherwise you need to explicitly use the goto case x statement)


Case 6:


Case 7:


Case 8:


monthstring = "Summer time!!";


Break


Default


monthstring = "Some other month";


Break


}

///////////////////////////////////////
The conversion string is an integer, and a conversion failure throws an exception:
///////////////////////////////////////

converting data

The conversion string is an integer, and a conversion failure throws an exception:
Int. Parse ("123");//return "123" of the integer type

TryParse will try the conversion type and return the default type when it fails, for example 0
int tryint;
if (int. TryParse ("123", out Tryint))//Funciton is Boolean
Console.WriteLine (Tryint); 123

Convert Integer to String
The Convert class provides a range of ways to facilitate conversions
Convert.ToString (123);
Or
Tryint.tostring ();
}

///////////////////////////////////////
Class
///////////////////////////////////////
public static void Classes ()
{
Refer to the object declaration at the end of the file

Initializing an object with new
Bicycle trek = New Bicycle ();

Method of calling Object
Trek. Speedup (3); You should always use the setter and Getter methods
Trek. Cadence = 100;

View information about the object.
Console.WriteLine ("Trek Info:" + trek.) Info ());

Instantiation of a new penny farthing
pennyfarthing funbike = new Pennyfarthing (1, 10);
Console.WriteLine ("Funbike info:" + funbike.) Info ());

Console.read ();
}//End Main method

The Terminal program Terminal program must have a main method as a portal
public static void Main (string[] args)
{
Otherinterestingfeatures ();
}

//
Interesting features
//

Default method signature

        public//visibility
        static// Allows you to call a class directly without first creating an instance
        int//return value
         Methodsignatures (
            int maxcount,// First variable, type int
            int count = 0,//If no value is passed in, the default value is 0
            int another = 3,
             params string[] Otherparams//Capture other parameters
        )
        {
             return-1;
       }

Method can be duplicate, as long as the signature is different
public static void Methodsignature (String maxcount)
{
}

Generic type


The TKey and TValue classes are specified by calling the function with the user.


The following function simulates the setdefault of Python


public static TValue Setdefault&lt;tkey, tvalue&gt; (


Idictionary&lt;tkey, Tvalue&gt; dictionary,


TKey Key,


TValue Defaultitem)


{


TValue result;


if (!dictionary. TryGetValue (key, out result))


return Dictionary[key] = Defaultitem;


return result;


}

       //You can limit the range of incoming values
        public static void Iterateandprint<t> (T toprint) where T:ienumerable<int>
         {
           //We can iterate, because T is enumerable
            foreach (var item in toprint)
                //Ittm is an integer
                 Console.WriteLine (item. ToString ());
       }

public static void Otherinterestingfeatures ()
{
Optional parameters
Methodsignatures (3, 1, 3, "Some", "Extra", "Strings");
Methodsignatures (3, Another:3); Explicitly specifying parameters, ignoring optional arguments

Extension methods
int i = 3;
I.print (); See the following definition

Nullable types can be useful for database interaction, return values,
Any value type (i.e. does not have a class) adds a suffix? Then it becomes a nullable type
< type? < variable name > = < value >
Int? nullable = NULL; Abbreviated form of nullable<int>
Console.WriteLine ("Nullable variable:" + Nullable);
BOOL HasValue = nullable. HasValue; Returns True when NOT NULL

// ?? Is the syntax sugar used to specify the default value
In case the variable is null
int notnullable = nullable?? 0; 0

Variable type inference
You can have the compiler infer the variable type:
var magic = "Magic is a string, at compile time, so you still get type safety";
Magic = 9; does not work because magic is a string, not an integer.

Generic type
//
var phonebook = new dictionary<string, string> () {
{"Sarah", "212 555 5555"}//Add a new entry in the phone book
};

Invoke the SetDefault defined above as a generic
Console.WriteLine (setdefault<string,string> (Phonebook, "Shaun", "No Phone")); No phone.
You don't have to specify TKey, TValue, because they are implicitly deduced.
Console.WriteLine (SetDefault (Phonebook, "Sarah", "No Phone")); 212 555 5555

Lambda expression-allows you to use a single line of code to fix a function
Func<int, int> square = (x) => x * x; The last entry is the return value
Console.WriteLine (Square (3)); 9

           //disposable resource management-makes it easy for you to handle resources that are not managed. Most access to managed resources (file operators, device contexts, etc.) objects, all of which implement the IDisposable interface. The
           //Using statement cleans up the IDisposable object for you.
            using (StreamWriter writer = new StreamWriter ("Log.txt"))
            {
                 writer. WriteLine ("There is nothing suspicious here");
               //At the end of the scope, the resource is reclaimed
               //(even if there are exceptions thrown, will be recycled as well)
           }

Parallel framework
Http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
var websites = new string[] {
"Http://www.google.com", "http://www.reddit.com",
"Http://www.shaunmccarthy.com"
};
var responses = new Dictionary<string, string> ();

Open a new thread for each request, merging the results before running the next step


Parallel.ForEach (Websites,


New ParallelOptions () {maxdegreeofparallelism = 3},//MAX of 3 threads


Website =&gt;


{


Do something this takes a long time on the file


using (var r = webrequest.create (new Uri (website)). GetResponse ())


{


Responses[website] = R.contenttype;


}


});

The following code will not run until all requests are completed
foreach (var key in responses). Keys)
Console.WriteLine ("{0}:{1}", Key, Responses[key]);

Dynamic objects (easy to use with other languages)
Dynamic student = new ExpandoObject ();
Student. FirstName = "The Name of"; You don't need to define a class first!

You can even add a method (accept a string, output a string)
Student. introduce = new func<string, string> (
(Introduceto) => string. Format ("Hey {0}, this is {1}", student.) FirstName, Introduceto));
Console.WriteLine (student. Introduce ("Beth"));

Iqueryable&lt;t&gt;-Almost all of the collections have achieved it, bringing you a map/filter/reduce style of approach


var bikes = new list&lt;bicycle&gt; ();


Bikes. Sort (); Sorts the array


Bikes. Sort (B1, B2) =&gt; b1.Wheels.CompareTo (B2. Wheels)); Sort by number of wheels


var result = Bikes


. Where (b =&gt; b.wheels &gt; 3)//filter-can be used in chain (return IQueryable)


. Where (b =&gt; b.isbroken &amp;&amp; b.hastassles)


. Select (b =&gt; b.tostring ()); MAP-Here we use the Select, so the result is iqueryable&lt;string

var sum = bikes. Sum (b => b.wheels); Reduce-Calculates the total number of wheels in a collection

           //Create a list of implicit objects that are generated by some parameters based on bicycles
             var bikesummaries = bikes. Select (b=>new {Name = b.name, isawesome =!b.isbroken && b.hastassles});
           //difficult to demonstrate, but the compiler can deduce the type of the above object before the code is compiled
            foreach (Var bikesummary in Bikesummaries.where ( b => b.isawesome))
                 Console.WriteLine (bikesummary.name);

AsParallel
The character of Evil--combining LINQ and parallel operations
var threewheelers = bikes. AsParallel (). Where (b => b.wheels = = 3). Select (b => b.name);
The code above will run concurrently. A new thread is automatically calculated and the results are computed separately. A scenario suitable for multi-core and large data volumes.

LINQ-Maps iqueryable<t> to storage, delaying execution, such as linqtosql mapping database, Linqtoxml mapping XML documents.
var db = new Bikerespository ();

Execution is delayed, which is good for querying the database
var filter = db. Bikes.where (b => b.hastassles); Do not run Query
if (> 6)//You can continuously add filters, including conditional filtering, for example, for advanced search features
Filter = filter. Where (b => b.isbroken); Do not run Query

var query = Filter
. by (b => b.wheels)
. ThenBy (b => b.name)
. Select (b => b.name); Still not running query

Now run the query, run the query will open a reader, so you iterate over a copy
foreach (string bike in query)
Console.WriteLine (result);

}

}//End Learncsharp class

You can include other classes in the same. cs file

public static Class Extensions
{
Extension functions
public static void Print (This object obj)
{
Console.WriteLine (obj. ToString ());
}
}

To declare the syntax of a class:
<public/private/protected/internal> Class < category name >{
Data fields, constructors, internal functions.
////In Java The function is called a method.
// }

public class Bicycle


{


The fields, variables of bicycles


public int Cadence//Public: Access is available anywhere


{


Getting//Get-defines methods for obtaining properties


{


return _cadence;


}


Set/Set-defines a method for setting properties


{


_cadence = value; Value is what is passed to the setter


}


}


private int _cadence;

protected virtual int Gear//classes and subclasses can access
{
Get Create an automatic property without the member fields
Set
}

internal int wheels//internal: Accessible in the same assembly
{
Get
Private set; You can add modifiers to the Get/set method
}

int _speed; Default is private: You can access only within this class, you can also use the ' private ' keyword
public string Name {get; set;}

The enum type contains a set of constants that map the name to a value (unless specifically described as an integral type).
The types of ENMU elements can be byte, sbyte, short, ushort, int, uint, long, and ulong. An enum cannot contain the same value.
public enum Bikebrand
{
AIST,
Bmc
Electra = 42,//You can assign values explicitly
Gitane//43
}
We define this type in the bicycle class, so it's an inline type. Code other than this class should be referenced using Bicycle.brand.

Public Bikebrand Brand; After declaring an enum type, we can declare a field of that type

static method
A static method is of its own type and does not belong to a particular object. You can access them without referencing the object.
static public int bicyclescreated = 0;

Read-only values
Read-only values are determined at run time, and they can only be assigned within a declaration or constructor.
readonly bool _hascardsinspokes = FALSE; Read-only Private

Constructors are a way to create a class.
The following is a default constructor.
Public Bicycle ()
{
This. Gear = 1; You can use the keyword this to access the members of the object
Cadence = 50; But you don't always need it.
_speed = 5;
Name = "Bontrager";
Brand = bikebrand.aist;
bicyclescreated++;
}

Example of another constructor (including parameters)


Public Bicycle (int startcadence, int startspeed, int startgear,


String name, bool Hascardsinspokes, Bikebrand brand)


: Base ()//First Call base


{


Gear = Startgear;


Cadence = startcadence;


_speed = Startspeed;


name = name;


_hascardsinspokes = Hascardsinspokes;


Brand = Brand;


}

Constructors can be chained to use
Public Bicycle (int startcadence, int startspeed, Bikebrand brand):
This is (startcadence, startspeed, 0, "Big Wheels", true, Brand)
{
}

function Syntax:
<public/private/protected> < return value > < function name > (< parameter >)

Classes can implement getters and setters methods for their fields for fields, or you can implement properties (C # recommends using this).

The parameter of the method can have a default value. In the case of a default value, the corresponding argument can be omitted when the method is invoked.
public void speedup (int increment = 1)
{
_speed + = increment;
}

public void slowdown (int decrement = 1)
{
_speed-= decrement;
}

property to access and set values. Consider using attributes when you only need to access the data. Properties can define get and set, or both.
private bool _hastassles; Private variable
public bool Hastassles//Public accessor
{
get {return _hastassles;}
set {_hastassles = value;}
}

You can define automatic properties within one line, and this syntax automatically creates fallback fields. You can set access modifiers to the getter or setter to restrict their access.
public bool IsBroken {get; private set;}

The implementation of a property can be automatic
public int Framesize
{
Get
You can specify access modifiers for GET or set
The following code means that only the bicycle class can call the Framesize set
Private set;
}

Ways to display Object properties


Public virtual string Info ()


{


Return "Gear:" + Gear +


"Cadence:" + Cadence +


"Speed:" + _speed +


"Name:" + name +


"Cards in Spokes:" + (_hascardsinspokes?) Yes ":" no ") +


"\ n------------------------------\ n"





}

The method can be static. Usually used for auxiliary methods.
public static bool Didwecreateenoughbycles ()
{
In a static method, you can only reference static members of a class
return bicyclescreated > 9000;
//If your class only needs static members, consider the entire class as a static class.

}//Bicycle class end

Pennyfarthing is a subclass of bicycle
Class Pennyfarthing:bicycle
{
(Penny farthings is a bicycle with a large front wheel.) No gears. )

       //Calling Parent builder
        Public pennyfarthing (int startcadence, int startspeed):
             Base (startcadence, Startspeed, 0, "pennyfarthing", True, Bikebrand.electra)
         {
       }

        protected override int Gear
         {
            get
             {
                 return 0;
           }
            Set
             {
                 throw new ArgumentException ("You can't switch gears on Pennyfarthing");
           }
       }

public override string Info ()
{
string result = "pennyfarthing bicycle";
result = base. ToString (); Calling the parent method
return result;
}
}

The interface contains only the signature of the member, but not the implementation.
Interface ijumpable
{
void Jump (int meters); All interface members are implicitly exposed
}

Interface ibreakable
{
BOOL broken {get;}//interface can contain properties, methods, and events
}

A class can inherit only one class, but it implements any number of interfaces
Class Mountainbike:bicycle, Ijumpable, ibreakable
{
int damage = 0;

public void Jump (int meters)
{
Damage + = meters;
}

        public bool Broken
        {
            Get
             {
                 return damage > 100;
           }
       }
   }

<summary>
Connect the database, a linqtosql example. EntityFramework Code A is great (similar to Ruby's ActiveRecord, but bidirectional)
Http://msdn.microsoft.com/en-us/data/jj193542.aspx
</summary>
public class Bikerespository:dbset
{
Public Bikerespository ()
: Base ()
{
}

Public dbset<bicycle> bikes {get; set;}
}
}//End Namespace

Note that the topics that are not covered are:
1.Flags
2.Attributes
3. Static properties
4.Exceptions, abstraction
6.asp.net (Web Forms/mvc/webmatrix)
6.Winforms
7.Windows presentation Foundation (WPF)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.