在 C# 中,可以使用各種方法來獲取數據,取決于數據的來源和類型。以下是一些常見的方法:
int num = 10;
Console.WriteLine(num); // 輸出 10
Console.ReadLine()
方法可以從用戶輸入中獲取數據。例如:Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[2]); // 輸出 3
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
foreach (var name in names)
{
Console.WriteLine(name);
}
using (var connection = new SqlConnection("connectionString"))
{
connection.Open();
using (var command = new SqlCommand("SELECT * FROM TableName", connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["ColumnName"]);
}
}
}
}
using (var client = new HttpClient())
{
var response = await client.GetAsync("https://api.example.com/data");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
Console.WriteLine(data);
}
}
這些是一些常見的方法,可以根據需要選擇合適的方法來獲取數據。