简体   繁体   中英

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. 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?

Jimmy

If I understand your question correctly, your properties of RootGroup are not being "lost". The issue is you have a Group view of a RootGroup object. In order to access RootGroup properties, you must cast the object to a 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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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