实现通用接口

时间:2014-06-06 15:18:37

标签: c# asp.net .net generics interface

任何人都可以帮助我通过接口暴露下面的类方法。我希望能够通过接口使用下面的Cache类方法。基本上需要创建一个通用缓存方法定义的通用接口,它们的实现将在下面的类

中提供
public  class CacheStore
{
    private  Dictionary<string, object> _cache;
    private  object _sync;

    public CacheStore()
    {
        _cache = new Dictionary<string, object>();
        _sync = new object();
    }

    public  bool Exists<T>(string key) where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            return _cache.ContainsKey(type.Name + key);
        }
    }

    public  bool Exists<T>() where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            return _cache.ContainsKey(type.Name);
        }
    }

    public  T Get<T>(string key) where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            if (_cache.ContainsKey(key + type.Name) == false)
                throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key));

            lock (_sync)
            {
                return (T)_cache[key + type.Name];
            }
        }
    }

    public  void Add<T>(string key, T value)
    {
        Type type = typeof(T);

        if (value.GetType() != type)
            throw new ApplicationException(String.Format("The type of value passed to 
            cache {0} does not match the cache type {1} for key {2}",     
            value.GetType().FullName, type.FullName, key));

        lock (_sync)
        {
            if (_cache.ContainsKey(key + type.Name))
                throw new ApplicationException(String.Format("An object with key '{0}'  
                already exists", key));

            lock (_sync)
            {
                _cache.Add(key + type.Name, value);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您可以按如下方式轻松提取界面。

interface ICache
{
    bool Exists<T>(string key) where T : class;
    bool Exists<T>() where T : class;
    T Get<T>(string key) where T : class;
    void Add<T>(string key, T value);
}

现在,您可以通过执行class CacheStore : ICache来使您的类实现它。


除此之外:您可以简单地将Dictionary密钥类型设为Tuple<Type, string>

,而不是使用密钥和类型名称的字符串连接。
private Dictionary<Tuple<Type, string>, object> _cache;

为了说清楚,以下是您可以通过此更改重新实现第一个Exists方法的方法:

public bool Exists<T>(string key) where T : class
{
    Type type = typeof(T);

    lock (_sync)
    {
        return _cache.ContainsKey(Tuple.Create(type, key));
    }
}

这将更加清晰,并且具有让您不必担心名称冲突的优势。根据您当前的设置,如果我添加了Location,其中包含密钥"FriendGeo",而GeoLocation添加了密钥"Friend",该怎么办?它们连接起来形成相同的字符串"FriendGeoLocation"。这可能看起来很人为,但如果最终发生这种情况,你会发现很难调试的非常奇怪(和错误)的行为。

答案 1 :(得分:0)

有一个工具可以在Visual Studio中自动执行此操作。在类中单击鼠标右键,选择Refactor,Extract Interface,Select All,Ok。

相关问题