【发布时间】:2021-10-15 09:45:57
【问题描述】:
我在使用 redis 通用缓存时遇到了一些问题,因为 redis 将值存储为 json,我必须将其反序列化到我的模型中,但我不能,因为我使用的是通用方法,我无法解决这个问题。
Redis 获取操作:
public T Get<T>(string key)
{
var type = typeof(T);
var result = default(object);
RedisInvoker(x => { result = x.Get<object>(key); });
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var deserializedObj = JsonConvert.DeserializeObject<T>(result.ToString(), settings);
return deserializedObj;
}
public object Get(string key)
{
var result = default(object);
RedisInvoker(x => { result = x.Get<object>(key); });
return result;
}
缓存拦截:
public override void Intercept(IInvocation invocation)
{
var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}");
var arguments = invocation.Arguments.ToList();
var key = $"{methodName}({string.Join(",", arguments.Select(x => x?.ToString() ?? "<Null>"))})";
if (_cacheManager.IsAdded(key))
{
invocation.ReturnValue = _cacheManager.Get(key);
return;
}
invocation.Proceed();
_cacheManager.Add(key, invocation.ReturnValue, _duration);
}
我想要做的是获取方法的 returnType 也是泛型的,并将其发送到具有泛型类型的 Get 方法。但我不能这样发送:
var returnType = invocation.Method.ReturnType;
if (_cacheManager.IsAdded(key))
{
invocation.ReturnValue = _cacheManager.Get<returnType>(key);
return;
}
错误是:
returnType 是一个变量,但用作类型
【问题讨论】:
-
if (invocation.Method.IsGenericMethod()) methodName+="<"+string.Join(",",invocation.Method.GetGenericArguments().Select(a => a.Name))+">";什么的... -
要拨打
Get<T>,您需要拨打methodinfo.MakeGenericMethod(type).Invoke(...)。改为添加.Get(Type t, ...)方法会更容易。 -
你能完整回答吗,我听不懂:/
标签: c# generics .net-core redis