Learn the basic c# knowledge required by ASP.NET
Author:Eve Cole
Update Time:2009-12-05 14:52:37
-
Microsoft's example textbook talks about three languages: c#, vb, and Jscript. In order to let everyone learn new things, let's learn c#. It is best to have some basic knowledge of C++.
But it doesn’t matter if you don’t have it, you’ll just have to put in a little more effort.
Any language has two parts:
Data + Grammar + Algorithm
Data is used to represent information, and syntax is used to control it. To put it bluntly, algorithms are some ways of thinking that people have summarized to solve problems. As for data, naturally there are data structures, and then there are queries, insertions, modifications, etc.
1. Of course, variables are used to store data. Now let’s talk about the declaration method in C#!
The usual method is:
Type + variable name
int x //Define an integer variable
string name,pwd; //Define two character variables
object x; //Define the object
object obj=new object();//Create an instance based on an object
public string x;//Add a type modifier to the character variable so that all users can access it
To explain:
When declaring variables, use lowercase for type words like int string object, because c# is strictly case-sensitive. It is wrong to use INT x; to define variables.
Let’s take a look at two programs:
/* Learn how to declare variables
create by vagrant */
using System;
class Test
{ static void Main()
{ int x=3;
Console.WriteLine("x={0}",x);
string name="vagrant";
string pwd="197926";
Console.WriteLine("your name is :{0};pwd is {1}",name,pwd);
object y;
y=x;//explicit conversion
Console.WriteLine("y={0}",y);
}
}
2. Send characters to the browser:
The above is about using System.Console.WriteLine to output the value of a variable in C#, but in ASP.NET you still need to use the Response.Write("char") method of the Response object, but you cannot omit the parentheses at this time.
example:
<%@ language="C#" %>
<% string name;
name="vagrant";
Response.Write("you name is "+name);
%>
3. Access the value of the index attribute (take the elements in the form as an example)
Friends who have learned asp know that you can use Requst.Form("object name") to extract the value of a form object. But in asp.net, use Request.QueryString["name"] to extract it.
4. Declare index attributes
In asp.net we need to learn event programming concepts and index indicators. Through the index pointer we can access the data information of the class like an array. Let's construct a simple example first:
using System;
classTeam
{
string[] s_name=new string[3]{"vagrant","jack","rose"};//Define a field of the class, and then write the constructor function so that the outer class can be accessed through the index
public string this[int nIndex]//Access index declaration
{
get {
return s_name[nIndex];//Provides foreign class read access
}
set {
s_name[nIndex]=value;//Provide foreign class writing rights
}
}
}
class Test
{
public static void Main(){
Team t1=new Team();//Create an instance of the Team class
for(int i=0;i<3;i++)
Console.WriteLine(t1[i]);//Access the data information of the instance through the index indicator
}
}
5. Define and initialize data
When we process batch data, we often use arrays. When defining an array, we need to consider three issues: type, data name, and dimension.
Let me use one-dimensional data as an example. After all, one-dimensional data is commonly used.
Define array:
string studentname[]=new string[50];
initialization:
Method one.
studentname[0]="vagrant";
studentname[1]="jack";
........
Method two.
int[] sex=new int[2]{0,1};//0 represents male, 1 represents female
This is easy to understand and I won’t explain it.
6. Structures and Enumerations
The reason why I talk about structures and enumerations together is because they have similarities and differences.
Structure: A collection of related information forming a single entity. An address book usually includes: name, phone number, address, etc.
Enumeration: A logically inseparable series of data. For example, there are days from Monday to Sunday in the week. But Monday to Sunday are logically inseparable.
There is a difference between the two. A structure is a collection of data, while an enumeration can only take one of them at a time. Structures and enumerations are both types of data structures.
Define structural data types:
struct PhoneBook {
public string name;
public string phone;
public string address;
}
Define a variable of this structure type
PhoneBook p1;
Assign values to each member of a structure variable
p1.name="vagrant";
p1.phone="88888888";
p1.address="wuhan";
Define enumeration data type and assign value
//Define an enumeration type
public enum MessageSize {
Small = 0,
Medium = 1,
Large = 2
}
//Create an enumeration type variable
public MessageSize msgsize;
//Assign a value to this variable
msgsize = Small;
7. Declare and use methods
//Define a function with no return value
void voidfunction() {
...
}
//Declare a subfunction with a return value
String stringfunction() {
...
return (String) val;//(string) indicates the return type
}
//Declare a function that can be calculated
String parmfunction(String a, String b) {
...
return (String) (a + b);
}
// use function
voidfunction();
String s1 = stringfunction();
String s2 = parmfunction("Hello", "World!");
8. Process control statements
There is not much difference between flow control statements in C# and C++. It's just that a foreach is added to C# (which should be familiar to vb programmers).
The worst thing about process control is selection and looping.
Usage of if conditional statement:
if(Requery.QueryString["name"]==null){
statement....
}
When there are too many choices, the switch statement is commonly used
Example:
switch (Name) {
case "John" :
...
break;
case "Paul" :
...
break;
case "Ringo" :
...
break;
default:
...
break;
}
There are usually two types of loop statements:
a.for loop
for (int i=0; i<3; i++){
statement...
}
b.while loop
int i = 0;
while (i<3) {
Console.WriteLine(i.ToString());//The purpose of i.ToString() is to convert i into a string type
i += 1;
}
9.Exception handling
When writing programs, we often encounter things that we cannot predict in advance. For example, user input errors, insufficient memory, unavailable network resources, unavailable databases, etc. So we should use exception handling methods to deal with such problems. All exceptions in C# are instances of a class, which inherits from the System.Exception class
Let’s first introduce the throw exception statement thow
throw expression
This statement is an exception generated when evaluating the expression
Exception handling statement:
try is used to catch exceptions that occur during block execution.
cathc is used to handle this exception.
General method:
try {
//Code that may throw an exception
} catch(OverflowException e) {
//Catch a detailed exception
} catch(Exception e) {
//Catch a common exception
} finally {
//Execute a code without exception
}
Take a look at an exception written by Beibei that handles database connection errors:
try
{
OleDbConnection conn = getConn(); //getConn(): Get the connection object
OleDbDataAdapter adapter = new OleDbDataAdapter();
string sqlstr="select id,title,author,pic,hits,posttime from notes order by posttime desc";
mydataset= new System.Data.DataSet();
adapter.SelectCommand = new OleDbCommand(sqlstr, conn);
adapter.Fill(mydataset,"notes");
conn.Close();
}
catch(Exception e)
{
throw(new Exception("Database error:" + e.Message))
}
10. String processing
In C#, string is a reference type, so you can use connection and truncation
You will know after reading the example below!
// use string
String s1;
String s2 = "hello";
s2 += "world";
s1 = s2 + "!!!";
//Use the Append method of the StringBuilder class
StringBuilder s3 = new StringBuilder();
s3.Append("hello");
s3.Append("world");
s3.Append("!!!");
11.Event handling
Events are members of a class that send notifications to the outside world.
Let’s first look at a representative example of event processing:
void MyButton_Click(Object sender,
EventArgs E) {
...
}
I don't know much about this. I heard that it will be clearer after watching MFC. If anyone has experience in this area, I hope you can give me some advice.
12. declare an event
//Create a public event
public event EventHandler MyEvent;
//Define a method for this event
protected void OnMyEvent(EventArgs e) {
MyEvent(this, e);
}
13. Add OR to the cause to handle the event.
Control.Change += new EventHandler(this.ChangeEventHandler);
Control.Change -= new EventHandler(this.ChangeEventHandler);
14.Type conversion
int i = 3;//Define an integer variable and assign a value
String s = i.ToString();//Convert integer to string type, use ToString()
double d = Double.Parse(s);//Convert string type to double precision type using Double.Parse(var);
There are some others that I won’t explain. Let’s dig into them after we have a certain foundation. Anyway, now that I understand these things, I will have no problem dealing with the common problems that follow.