C# キャッシュとは?基本と実装方法をやさしく解説

C#では、MemoryCacheクラスを使用してキャッシュ機能を実装することができます。以下は簡単な例です:

using System;
using System.Collections.Generic;
using System.Runtime.Caching;

class Program
{
    static void Main()
    {
        // 创建一个MemoryCache实例
        MemoryCache cache = MemoryCache.Default;

        // 添加一个缓存项,键为"key",值为"value",缓存时间为10分钟
        cache.Add("key", "value", DateTimeOffset.Now.AddMinutes(10));

        // 从缓存中获取值
        string cachedValue = cache.Get("key") as string;
        if (cachedValue != null)
        {
            Console.WriteLine("Value from cache: " + cachedValue);
        }
        else
        {
            Console.WriteLine("Value not found in cache.");
        }

        // 移除缓存项
        cache.Remove("key");
    }
}

上記の例では、まずMemoryCacheオブジェクトをインスタンス化し、Addメソッドを使用してキー、値、および有効期限を指定してキャッシュ項目をキャッシュに追加しています。その後、Getメソッドを使用してキャッシュから値を取得し、出力します。最後に、Removeメソッドを使用してキャッシュ項目を削除します。これにより、簡単にキャッシュ機能を実装することができます。

bannerAds