1.变量声明和使用:
2.条件语句(if-else):
3.循环语句(for):
4.数组声明和访问:
5.方法声明和调用:
6.类声明和实例化:
7.文件导入和命名空间使用:
8.异常处理:
C#:
string name = "John";
int age = 25;
Console.WriteLine("My name is {0} and I am {1} years old.", name, age);
2.条件语句(if-else):
C#:
int score = 85;
if (score >= 60)
{
Console.WriteLine("You passed the exam!");
}
else
{
Console.WriteLine("You failed the exam.");
}
3.循环语句(for):
C#:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Number: {0}", i);
}
4.数组声明和访问:
C#:
string[] fruits = { "apple", "banana", "orange" };
Console.WriteLine(fruits[0]); // 输出 "apple"
5.方法声明和调用:
C#:
void Greet(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
Greet("Alice"); // 输出 "Hello, Alice!"
6.类声明和实例化:
C#:
class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
public void Greet()
{
Console.WriteLine("Hello, my name is {0}!", name);
}
}
Person person = new Person("John");
person.Greet(); // 输出 "Hello, my name is John!"
7.文件导入和命名空间使用:
C#:
// 文件1.cs
public class MyClass
{
public string Variable = "Hello from file 1!";
}
// 文件2.cs
using System;
using YourNamespace;
class Program
{
static void Main()
{
MyClass myObject = new MyClass();
Console.WriteLine(myObject.Variable); // 输出 "Hello from file 1!"
}
}
8.异常处理:
C#:
public double Divide(int numerator, int denominator)
{
if (denominator == 0)
{
throw new Exception("Division by zero error!");
}
return (double)numerator / denominator;
}
try
{
Console.WriteLine(Divide(10, 0));
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
最后编辑: