首页 新闻 赞助 找找看

.net 如何在AOP的拦截器里使用泛型

0
悬赏园豆:50 [已解决问题] 解决于 2018-09-12 15:47


或者如何 Redis 在 AOP 的结合使用

老张的哲学的主页 老张的哲学 | 初学一级 | 园豆:2
提问于:2018-09-12 10:43
< >
分享
最佳答案
0

泛型的类型是在编译时确定的,无法在运行时指定泛型的类型

收获园豆:50
dudu | 高人七级 |园豆:31075 | 2018-09-12 10:53

因为我现在想把字符串反序列化成对象,所以这里必须指明对象类型,是不是没有什么办法了
或者说
您有什么办法,可以在 拦截器这里 将字符串 反序列化成 对象呢

老张的哲学 | 园豆:2 (初学一级) | 2018-09-12 10:58

@老张的哲学: json反序列化还是二进制反序列化?

dudu | 园豆:31075 (高人七级) | 2018-09-12 11:07

@dudu: Json,就是一个对象转字符串,然后现在想 在拦截器里 把字符串给反序列成对象返回过去

老张的哲学 | 园豆:2 (初学一级) | 2018-09-12 11:13

@老张的哲学: json反序列化必须要指定类型,如果不无法指定类型,只能使用 dynamic 类型

dudu | 园豆:31075 (高人七级) | 2018-09-12 11:19

@dudu:那这样的话,我直接用 object 也是一个道理吧

老张的哲学 | 园豆:2 (初学一级) | 2018-09-12 11:30

@老张的哲学: JsonConvert.DeserializeObject(json) 出来的类型是 Newtonsoft.Json.Linq.JObject

dudu | 园豆:31075 (高人七级) | 2018-09-12 12:04
其他回答(1)
0

public static class MemoryCacheExtensions
{
private static ConcurrentDictionary<string, object> _lockLookup = new ConcurrentDictionary<string, object>();
public static async Task<TItem> GetOrCreateExclusiveAsync<TItem>(this IMemoryCache cache, string key, Func<MemoryCacheEntryOptions, Task<TItem>> factory, bool cacheNullValue = true)
{
if (!cache.TryGetValue(key, out var result))
{
using (await AsyncLock.GetLockByKey(key).LockAsync())
{
if (!cache.TryGetValue(key, out result))
{
var options = cache is IStorefrontMemoryCache storefrontMemoryCache ? storefrontMemoryCache.GetDefaultCacheEntryOptions() : new MemoryCacheEntryOptions();
result = await factory(options);
if (result != null || cacheNullValue)
{
cache.Set(key, result, options);
}
}
}
}
return (TItem)result;
}

    public static TItem GetOrCreateExclusive<TItem>(this IMemoryCache cache, string key, Func<MemoryCacheEntryOptions, TItem> factory, bool cacheNullValue = true)
    {
        if (!cache.TryGetValue(key, out var result))
        {
            lock (_lockLookup.GetOrAdd(key, new object()))
            {
                if (!cache.TryGetValue(key, out result))
                {
                    var options = cache is IStorefrontMemoryCache storefrontMemoryCache ? storefrontMemoryCache.GetDefaultCacheEntryOptions() : new MemoryCacheEntryOptions();
                    result = factory(options);
                    if (result != null || cacheNullValue)
                    {
                        cache.Set(key, result, options);
                    }
                }
            }
        }
        return (TItem)result;
    }
}

这个怎么能改进用Redis实现

LDAR泄漏检测与修复 | 园豆:406 (菜鸟二级) | 2020-02-05 18:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册