C# 实现通用接口
有谁能帮助我通过接口公开下面的类方法吗。我希望能够通过接口使用下面的缓存类方法。基本上,我们需要创建一个通用接口,其中定义了公共缓存方法,它们的实现将在下面的类中提供C# 实现通用接口,c#,asp.net,.net,generics,interface,C#,Asp.net,.net,Generics,Interface,有谁能帮助我通过接口公开下面的类方法吗。我希望能够通过接口使用下面的缓存类方法。基本上,我们需要创建一个通用接口,其中定义了公共缓存方法,它们的实现将在下面的类中提供 public class CacheStore { private Dictionary<string, object> _cache; private object _sync; public CacheStore() { _cache = new Dictio
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);
}
}
}
}
您可以按如下方式轻松提取接口
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);
}
为了说明这一点,您可以通过以下更改重新实现您的第一个现有方法:
public bool Exists<T>(string key) where T : class
{
Type type = typeof(T);
lock (_sync)
{
return _cache.ContainsKey(Tuple.Create(type, key));
}
}
这将是一个稍微干净,并有一个优势,让您不必担心名称冲突。在您当前的设置中,如果我添加了一个带有key FriendGeo的位置和一个带有key Friend的位置,该怎么办?它们都连接在一起形成相同的字符串FriendGeoLocation。这可能看起来是人为的,但如果它真的发生了,您将得到非常奇怪和错误的行为,这将很难调试。Visual Studio中有一个自动执行此操作的工具。在类中单击鼠标右键,选择“重构”,提取接口,选择“全部”,确定。什么接口?不清楚您要问什么。只需将方法签名提取到接口中,删除public,给接口一个名称,您就完成了
public bool Exists<T>(string key) where T : class
{
Type type = typeof(T);
lock (_sync)
{
return _cache.ContainsKey(Tuple.Create(type, key));
}
}