我有一个用于检查方法参数的类,您可以以以下形式调用该类:
public void SomeMethod(string anArg)
{
Ensure.ArgumentNotNull(() => anArg);
}
如果参数为null,则抛出具有属性名称的ArgumentNullException
。这样做:
public static void ArgumentNotNull<T>(Expression<Func<T>> expression) where T : class
{
var value = expression.Compile()();
if (value == null)
{
throw new ArgumentNullException(expression.GetMemberName());
}
}
其中<code>GetMemberName</code>是我编写的一个扩展方法。
我遇到的问题是,对Compile的调用非常慢,所以我想缓存结果,但我似乎无法找到一个足够唯一的缓存密钥来防止缓存冲突,但又不能唯一到使缓存无效。
到目前为止,我最大的努力是:
internal static class ExpressionCache<T>
{
private static readonly Dictionary<string, Func<T>> Cache = new Dictionary<string, Func<T>>();
public static Func<T> CachedCompile(Expression<Func<T>> targetSelector)
{
Func<T> cachedFunc;
var cacheKey = targetSelector + targetSelector.Body.ToString();
if (!Cache.TryGetValue(cacheKey, out cachedFunc))
{
cachedFunc = targetSelector.Compile();
Cache[cacheKey] = cachedFunc;
}
return cachedFunc;
}
}
但这仍然会导致缓存密钥冲突。什么可能是更好的方法?