📅  最后修改于: 2023-12-03 15:40:09.697000             🧑  作者: Mango
作为程序员,我们在开发过程中可能会遇到各种各样的问题,需要用到各种各样的代码片段。在这里,我分享一些常用的C#代码片段,帮助大家解决问题。
public class Animal {
public virtual void Eat() {}
}
public class Dog : Animal {
public override void Eat() {}
}
public class Animal {
public virtual void Eat() {}
}
public class Dog : Animal {
public override void Eat() {}
}
public class Cat : Animal {
public override void Eat() {}
}
Animal animal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();
animal.Eat(); // 调用Animal的Eat方法
dog.Eat(); // 调用Dog的Eat方法
cat.Eat(); // 调用Cat的Eat方法
public interface IAnimal {
void Eat();
}
public class Dog : IAnimal {
public void Eat() {}
}
public class Cat : IAnimal {
public void Eat() {}
}
try {
// 可能出现异常的代码
} catch (Exception ex) {
// 处理异常
}
try {
// 可能出现异常的代码
} catch (Exception ex) {
// 处理异常
} finally {
// 必定执行的代码
}
public int Divide(int a, int b) {
if (b == 0) {
throw new DivideByZeroException();
}
return a / b;
}
string str1 = "hello";
string str2 = "world";
string result = str1 + " " + str2;
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
// 相等
} else {
// 不相等
}
string str = "hello world";
str = str.Replace("world", "C#");
string str = "hello,world";
string[] arr = str.Split(',');
string filePath = @"c:\test.txt";
using (StreamWriter writer = File.CreateText(filePath)) {
writer.WriteLine("hello world");
}
string filePath = @"c:\test.txt";
using (StreamReader reader = File.OpenText(filePath)) {
string content = reader.ReadToEnd();
}
string url = "http://example.com";
using (WebClient client = new WebClient()) {
string result = client.DownloadString(url);
}
string url = "http://example.com";
string postData = "name=Tom&age=20";
using (WebClient client = new WebClient()) {
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string result = client.UploadString(url, postData);
}
上述代码片段只是众多C#代码片段中的一部分。希望这些代码片段能帮助大家更快地解决问题,提高开发效率。