在C#中,為了簡化操作,您可以使用以下方法:
List<int>
,您可以使用LINQ輕松地篩選出其中的偶數:using System.Collections.Generic;
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
string
類型添加一個名為ToUpperAsync
的方法:using System.Threading.Tasks;
public static class StringExtensions
{
public static Task<string> ToUpperAsync(this string input)
{
return Task.Run(() => input.ToUpper());
}
}
async
和await
關鍵字從Web API獲取數據:using System.Net.Http;
using System.Threading.Tasks;
public async Task<string> GetDataFromApiAsync(string url)
{
using (HttpClient client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
// ...
}
public class MyService
{
private readonly MyDbContext _dbContext;
public MyService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
// ...
}
var services = new ServiceCollection();
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<MyService>();
var serviceProvider = services.BuildServiceProvider();
var myService = serviceProvider.GetService<MyService>();
通過使用這些方法,您可以簡化C#代碼,使其更易于閱讀和維護。