search
HomeBackend DevelopmentC#.Net TutorialDetailed introduction to the basic knowledge of C# in ASP.NET

This article mainly introduces the basic knowledge of C# in ASP.NET. It has a certain reference value, let’s take a look with the editor below

Explanation: asp.net as a developmentframework is now widely used, and its development foundation is in addition to the front-end The most important language support for backends such as html, css, JavaScript, etc. is C#. The following is a summary of the main basic knowledge used for future learning.

1. C# is an object-orientedprogramming language, mainly used to develop applications that can run on the .net platform. is a strongly typed language, so every variable must have a declared type. There are two data types in C#: value types and reference types. (Where value types are used to store values, reference types are used to store references to actual data).

1. Value type

The value type represents the actual data and is stored in the stack. Most basic types in C# are numeric types. Value types include simple types, enumeration types, and structure types.

Simple types include numerical types and bool types. (Generally, choose the numeric type according to your needs. When the value is small, you can try to choose the byte type).

2. Reference type

The reference type represents a pointer or reference to data and can store references to actual data. When the reference type is null, it means that no object is referenced. Reference types include interfaces, classes, arrays, pointers, etc. The classes include boxing types, delegates, and custom classes. (Note: Although string is an application type, if the equality operator == or != is used, it means comparing the value of the string object).

3. Boxing and unboxing

Simply put, boxing is the conversion from value type to reference type. Likewise, unboxing is a conversion from a reference type to a value type. Using unboxing, you can operate complex reference types just like simple types, which is also a powerful feature of C#.

Simple examples of boxing and unboxing

class Test
 {
 static void Mian()
 {
  int i = 3;
  object a = i;//装箱
  int j = (int)a;//拆箱
 }
 }

Explanation: During the process of boxing and unboxing, any value type can be viewed as an object reference type. When a boxing operation converts a value type to a reference type, there is no need to explicitly cast the type; while an unboxing operation converts a reference type to a value type, because it can force Convert to any compatible value type, so the type conversion must be done explicitly.

2. Constants and variables

1. Constants: also known as constants, are known at compile time and do not change during operation. Quantities and constants are declared as fields. When declaring, use the

const keyword in front of the type of the field. The constant must be initialized when declaring. Constants can be marked as public, private, protected, internal, protected internal. These access modifiers define how users can access the constant.

2. Variables: The naming rules of variables must comply with the naming rules of the logo, and

variable names should be as meaningful as possible for easy reading. Variables are quantities whose values ​​continuously change during the running of the program. They are usually used to save the data input during the running of the program, the intermediate results obtained by calculations, and the final results.

Variables must be declared before using them. Variables can save a value of a given type. When declaring a variable, you also need to specify its name. The form of declaring variables: [access modifier data type variable name].

Modifier access level:

public: Makes the member accessible from anywhere

protected: Makes the member accessible from the class in which it is declared and Internal access in its derived classes

private: Makes the member accessible only from within the class in which it is declared

internal: Makes the member accessible only from within the assembly in which it is declared

3. Type conversion

1. Implicit type conversion

Implicit type conversion means that it can be performed without declaration. conversion performed. When doing an implicit conversion, the compiler can

safely perform the conversion without checking.

                                      隐式类型转换表
源类型 目标类型
sbyte short, int long double decimal
byte short,ushort,int uint,ulong,float,double,decimal
short int ,long,float,double,decimal
ushort int ,uint,long ,ulong,float,double,decimal
int  long float,double,decimal
uint long ulong float double decimal
char ushort int unit long float double decimal 
float double
ulong  float double decimal
long  float double decimal

Note: Precision loss will occur when converting from int long ulong float simple type to float.

2. Explicit type conversion

Explicit type conversion can also be called forced type conversion, which requires Declare the type to be converted. If you are converting between types for which no implicit conversion exists, you need to use an explicit type conversion.

Forced type conversion can use the Convert keyword to force data type conversion.

For example: float f=123.345;

int i=(int)f;

Or: float f=123.345

int i=Convert. ToInt32(f);

Note: Since explicit type conversion includes all implicit type conversions and explicit type conversions, cast type conversion can always be used at one timeExpressionFrom Converts any numeric type to any other numeric type.

4. Operators and expressions

C# provides a large number of operators, which specify which operations are performed in expressions symbol. An expression is a piece of code that can be evaluated and results in a single value, object, method, or namespace.

1, Arithmetic operators and arithmetic expressions

Arithmetic operators include + - * / and %. (It’s too simple and I won’t go into details here);

2. Relational operators and relational expressions

Relational operators include: ! = == = etc. (all languages ​​are the same);

3, Assignment operator and assignment expression

The assignment operator is used to assign a new value to a variable,

attribute, event, or index element. Commonly used ones include: =, +=, -=, *=, /=, ^=, %=, >= (left shift assignment), etc.

4, Logical operators and logical expressions

Logical operators include: & (AND operator) , ^ (XOR operator), ! (not operator), | (OR operator), use logical operators to connect the operands.

5, bit operator

The bit operator refers to treating its operand as a binary set , each binary bit can take the value 0 or 1. >Move right.

6. Other operators

Increment and decrement operators: ++, --, a--, a++.

Conditional operator:? : Returns one of two values ​​based on the value of a Boolean expression. For example: int a=1; int b=2; a!=b?a++:a--; (If a!=b, this instance returns an execution result of 2, otherwise it is 1).

new operator: used to create objects and call constructors. For example: int i=new int(); is equivalent to int i=0;

as operator: used to perform conversions between compatible reference types. For example: string s =someObject as string; The as operator is similar to a cast. When the conversion fails, the operator produces a null value instead of raising a null value.

7. Priority of operators

Basic>>Singular>>Multiplication and division>>Addition and subtraction> ;> Shift >> Compare > Conditions>>Assignment

5. String processing

##1. Compare stringsString class provides a series of methods for string comparison, such as CompareTo and Equals.

The CompareTo method is used to compare whether two strings are equal. Format: String.CompareTo(String); Return numeric type

The Equals method is used to determine whether two string objects have the same value. Format: String.Equals(String); Returns Boolean type

2, positioning and its string Someone in the positioning string Use the IndexOf method at the position where the character or Zichuan first appears. Format: String.IndexOf(String); the parameters represent the string to be located. (Pay attention to capitalization).

3, Format string

.Net提供了一种灵活全面的方式,能够将任何数值、枚举、日期时间等基本数据类型表示为字符串。格式化由格式说明符的字符串表示,该字符串指示如何表示基类型。

格式为:String Format(String,Object);例如:

//格式化为Currency类型
string str1=String.Format("(C)Currency:{0:C}\n",-123.4556f);
//格式化为ShortDate类型
string str2=String.Format("(d)ShortDate:{0:d}\n",DateTime.Now);

4、截取字符串

SubString方法可以从指定字符串中截取子串。格式:String.SubString(Int32,Int32);  第一个参数表示子串的起始位置,第二个参数表示子串的结束位置。

5、分裂字符串

Split()方法可以把一个字符串按照某个分隔符分裂成一系列小的字符串。格式:String []Split(char[]);参数为分割字符串的数组。

string str="hello world";
string[] split=str.Split(new Char[]{'.','!'});
foreach(string s in split)
{
 if(s.Tirm()!='''')
 {
 Console.WriteLine(s);
 }
//或者修改为
 string []split=str.Split(','.'!');

6、插入和填充字符串

插入字符串:Insert()方法,用于在一个字符串的指定位置插入另外一个字符串,从而构造一个新的字符串。格式:String.Insert(int,String);第一个参数为指定插入的位置。

填充字符串:PadLeft()方法和PadRight()方法添加指定数量的空格实现左右对齐。格式:String PadLeft(int,char)。String PadRight(int Char);

7、删除和剪切字符串

删除字符串:Remove()方法用于在一个字符串的指定位置删除指定的字符。格式:String Remove(int ,int);第一个参数表示删除的位置,第二个参数表示删除字符的数量。

剪切字符串:常用的剪切首位的多余字符用到的方法有: Trim(),TrimStart(),TrimEnd();格式如下:

String Trim(Char[]);//从字符串的开头和结尾处一处空白。
String TrimStart(Char[]);//从字符串的开头处移除字符串在字符数组中指定的字符。
String TrimEnd(Char[]);//从字符串的结尾处移除字符数组中指定的字符。

8、复制字符串

Copy()方法可以把一个字符串复制到另一个字符串中。格式:String Copy(String);//参数为需要复制的字符串,方法返回目标字符串。

9、替换字符串

Replace()方法可以替换掉一个字符串中的某些特定的字符或者子串。格式:String Replace(string ,string );第一个参数为待替换子串,第二工人参数为替换后的新子串。

六、流程控制

1、分支语句

1>if... else语句

if(布尔表达式)

{  代码片段1}

else{  代码片段2}

2>switch语句

switch(条件)

{   case 条件1:

     break;

   '''''

}

2、循环语句

for()循环

while()语句

do while语句

foreach语句

3、异常处理语句

try.....catch语句

try.....finally语句,finally块用于清除try块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码。控制总是传递给finally块,与try块的退出方式无关。

try...catch..finally语句

throw语句,用于立即无条件地引发异常,控制永远不会到达紧跟在throw后面的语句。

七、数组

数组是从System.Array派生的引用类型。

1、数组的声明:

一般语法:type[]arrayName;type[,]arrayName;

2、初始化数据(数组初始化的方式很多,可以通过new运算符创建数组元素初始化为它们的默认值)

//举例
int []arr=new int[6];
int [,]arr=new int[2,3];
int []arr1=new int[3]{1,2,3};
int [,]arr2=new int[3,2]{{2,3},{5,5},{3,5}};
string []arr;
arr=new string[3]{"sd","dddd","aaaa"};
int [,]arr;
arr=new int[,]{{2,3},{4,5},{4,2}};
//创建数组时可以省略new和数组长度
string[]arr={"ddd","fff","sss"};
int [,]arr3={{2,3},{4,5},{3,2}};

3、数组的遍历

C#用foreach语句进行遍历数组,是一种简单的明了的方法来循环访问数组中的元素。

int []arr={2,3,6,3,2};
foreach(int i in arr){
 system.Console.write({0},i);
}

掌握以上的基本知识简单的asp.net开发后台部分就成功了一部分,学无止境。

The above is the detailed content of Detailed introduction to the basic knowledge of C# in ASP.NET. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.