简体   繁体   English

在.NET中,为什么ObjectCache比MemoryCache是​​首选类型?

[英]In .NET, why is ObjectCache the preferred type over MemoryCache?

So many examples of using the memory cache in .NET ( including the official docs ) instantiate it with: 所以 很多 的例子使用.NET中的内存缓存(的包括官方文档 )与实例吧:

private readonly ObjectCache memoryCache = MemoryCache.Default;

Is there any reason to prefer this over: 有什么理由要优先于此:

private readonly MemoryCache memoryCache = MemoryCache.Default;

It's similar to declaring a variable or receiving a parameter of type Stream rather than FileStream or MemoryStream : the flexibility of not having to care which implementation you have. 这类似于声明变量或接收Stream类型而不是FileStreamMemoryStream类型的参数:不必关心您拥有哪种实现的灵活性。

ObjectCache is the base class of MemoryCache . ObjectCacheMemoryCache的基类。 At instantiation, you're creating a specific implementation, but elsewhere in your code, it shouldn't matter which implementation you have. 在实例化时,您正在创建一个特定的实现,但是在代码的其他地方,使用哪个实现则无关紧要。 What matters is the common interface provided by the base class. 重要的是基类提供的通用接口。 You can change the instantiation to create a different type and the code that uses the cache doesn't have to be modified. 您可以更改实例化以创建其他类型,并且不必修改使用缓存的代码。

The reason to prefer ObjectCache over MemoryCache is the L in SOLID... 选择ObjectCache不是MemoryCache的原因是SOLID中的L ...

Liskov substitution principle: Liskov替代原则:

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. 程序中的对象应该可以用其子类型的实例替换,而不会改变该程序的正确性。

ObjectCache is replaceable by any of its subtypes including MemoryCache while MemoryCache is not replaceable by anything forcing you into a specific implementation. ObjectCache可以用其任何子类型(包括MemoryCache替换,而MemoryCache不能用任何迫使您进入特定实现的方法替换。

ObjectCache is a abstract class so you cant directly instantiate it and demonstrates how you should build a Cache that adheres to the rules the person who wrote ObjectCache wants you to obey. ObjectCache是​​一个抽象类,因此您不能直接对其进行实例化,并演示如何构建符合编写ObjectCache的人员希望您遵守的规则的Cache。

So that MemoryCache inherits from ObjectCache. 这样MemoryCache继承自ObjectCache。 For everyday use you would use MemoryCashe. 对于日常使用,您可以使用MemoryCashe。 But if you want to your own you could inherit from objectCashe and write your own methods. 但是,如果您想要自己的,可以从objectCashe继承并编写自己的方法。

public class MemoryCache : ObjectCache, 
IEnumerable, IDisposable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM