简体   繁体   English

ASP.NET中的继承和缓存

[英]Inheritance and caching in ASP.NET

I've got some class hierarchy - base class which is named "Group", which contains base information about single group, and class named "RootGroup" which inherits from "Group" and extend base class with some properties. 我有一些类层次结构-名为“ Group”的基类,其中包含有关单个组的基本信息,以及名为“ RootGroup”的类,该类继承自“ Group”,并使用某些属性扩展了基类。 List of groups is stored in the cache using base class: eg IEnumerable (some of them are ordinary groups, and some of them are root groups. The point is when the collection is being retrieved from the cache and cast back to IEnumerable type, specific information of RootGrop items are lost. Is there any way to prevent this situation except of remembering type of each cached item? 组列表使用基类存储在高速缓存中:例如IEnumerable(其中一些是普通组,一些是根组。关键是从缓存中检索集合并将其强制转换回IEnumerable类型,具体RootGrop项目的信息丢失了,除了记住每个缓存项目的类型之外,是否有其他方法可以防止这种情况发生?

Jimmy 吉米

If I understand your question correctly, your properties of RootGroup are not being "lost". 如果我正确理解您的问题,那么您的RootGroup属性不会“丢失”。 The issue is you have a Group view of a RootGroup object. 问题是您具有RootGroup对象的Group视图。 In order to access RootGroup properties, you must cast the object to a RootGroup . 为了访问RootGroup属性,必须将对象RootGroup转换为RootGroup

A simple check: 一个简单的检查:

 if(groupItem is RootGroup)
 {
       RootGroup rootGroupItem = groupItem as RootGroup;
       // Do stuff
 } 

You can check each item as you retrieve it, and cast it to its proper type: 您可以在检索每个项目时对其进行检查,并将其转换为正确的类型:

foreach (object item in list) {
  if (item is RootGroup) {
    Rootgroup rootGroup = item as RootGroup;
    // do stuff  with rootGroup 
  }
}

If you are using a generic collection, like a List<Group> , you can change the foreach like this: 如果您使用的是通用集合,如List<Group> ,则可以这样更改foreach:

foreach (Group item in list)...

Another way... 其他方式...

//from cache
IEnumerable<Group> groupsFromCache = GetGroupsFromCache();
IEnumerable<RootGroup> rootGroups = groupsFromCache.OfType<RootGroup>();

See http://www.thinqlinq.com/default/Using-Cast-Or-OfType-Methods.aspx 参见http://www.thinqlinq.com/default/Using-Cast-Or-OfType-Methods.aspx

This has various niceties associated with deferred execution, but without more detail I can't really tell if that makes a difference. 这具有与延迟执行相关的各种优点,但是如果没有更多细节,我无法真正分辨出是否有区别。 And like other posts noted, your information associated with the child class is not lost, you just need to put it in a form where its accessible. 就像提到的其他帖子一样,与子类相关的信息也不会丢失,您只需将其放在可访问的形式即可。

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

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