c#

如何在C#中使用Attribute来实现缓存功能

小樊
86
2024-08-12 04:43:40
栏目: 编程语言

在C#中使用Attribute来实现缓存功能可以通过自定义一个Attribute类来实现。以下是一个简单的例子:

using System;

[AttributeUsage(AttributeTargets.Method)]
public class CacheAttribute : Attribute
{
    public int CacheDuration { get; set; }

    public CacheAttribute(int duration)
    {
        CacheDuration = duration;
    }
}

public class MyService
{
    [Cache(60)] // 缓存60秒
    public string GetData()
    {
        // 从缓存中获取数据,如果缓存过期则重新获取数据并存入缓存
        return "Cached data";
    }
}

public class CacheManager
{
    public static object GetCachedData(Func<object> method, CacheAttribute attribute)
    {
        // 检查缓存是否过期
        // 如果过期则调用方法获取数据并存入缓存
        return method();
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyService myService = new MyService();
        var method = typeof(MyService).GetMethod("GetData");
        var attribute = (CacheAttribute)Attribute.GetCustomAttribute(method, typeof(CacheAttribute));

        object data = CacheManager.GetCachedData(() => myService.GetData(), attribute);
        Console.WriteLine(data);
    }
}

在上面的例子中,我们定义了一个CacheAttribute来标记需要缓存的方法,并在MyService类中使用了该Attribute。在CacheManager类中,我们定义了一个静态方法GetCachedData来处理缓存逻辑。在Program类中,我们获取了GetData方法上的CacheAttribute,然后通过CacheManager来获取数据并输出。

0
看了该问题的人还看了