C#:是否可以使用表达式或函数作为字典中的键?

发布于 2024-07-27 12:00:17 字数 939 浏览 5 评论 0 原文

使用 Expression>Func 作为字典中的键是否有效? 例如缓存大量计算的结果。

例如,从我的不同问题更改我的非常基本的缓存一点:

public static class Cache<T>
{
    // Alternatively using Expression<Func<T>> instead
    private static Dictionary<Func<T>, T> cache;
    static Cache()
    {
        cache = new Dictionary<Func<T>, T>();
    }
    public static T GetResult(Func<T> f)
    {
        if (cache.ContainsKey(f))
            return cache[f];

       return cache[f] = f();
    }
}

这还能用吗?

编辑:经过快速测试,看起来它确实有效。 但我发现它可能更通用,因为它现在是每个返回类型一个缓存...不知道如何更改它以免发生这种情况...嗯

编辑2:不,等等...实际上不是。 嗯,对于常规方法来说确实如此。 但不适用于 lambda。 即使它们看起来相同,它们也会获得各种随机方法名称。 哦,好吧 c",)

Would it work to use Expression<Func<T>> or Func<T> as keys in a dictionary? For example to cache the result of heavy calculations.

For example, changing my very basic cache from a different question of mine a bit:

public static class Cache<T>
{
    // Alternatively using Expression<Func<T>> instead
    private static Dictionary<Func<T>, T> cache;
    static Cache()
    {
        cache = new Dictionary<Func<T>, T>();
    }
    public static T GetResult(Func<T> f)
    {
        if (cache.ContainsKey(f))
            return cache[f];

       return cache[f] = f();
    }
}

Would this even work?

Edit: After a quick test, it seems like it actually works. But I discovered that it could probably be more generic, since it would now be one cache per return type... not sure how to change it so that wouldn't happen though... hmm

Edit 2: Noo, wait... it actually doesn't. Well, for regular methods it does. But not for lambdas. They get various random method names even if they look the same. Oh well c",)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柒七 2024-08-03 12:00:18

您可以使用任何类型的对象,只要它是实例即可。 即使是委托,但我不建议使用委托作为键,因为它们不是为此设计的。 我不确定独立创建的委托会产生相同的哈希码,如果可以比较(可相等),甚至会更少。

You can use any type of object, as long as it is an instance. That even being a delegate, but I do not recommend using delegates as keys because they are not designed for that. I'm not sure that independently created delegates produce the same hash code, even less if they can be compared (equatable).

遗心遗梦遗幸福 2024-08-03 12:00:18

这可能有些牵强,但使用动态语言运行时(IronPython 等),您绝对可以运行字典中的任意代码片段。

然后,您可以根据需要动态运行代码,第一次缓存结果,并将缓存的结果用于以后的所有调用。

如果你有大量的计算,我敢打赌这最终会表现得很好。 但这都是视情况而定的,我不确定您到底想要实现什么目标。 :)

This might be a stretch, but using the Dynamic Language Runtime (IronPython, etc) you could definitely run arbitrary code snippets from a dictionary.

Then you could run the code on the fly as needed, cache the result the first time, and use the cached result for all future calls.

If you had a lot of computations, I bet this would end up performing pretty well. It's all situational though, and I'm not sure exactly what you're trying to achieve. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文