3

I'm using C# 4.0, Asp.Net. I have a problem regarding the proper construction of a readonly structure within a custom cache I created.

Details (summary) :
My CacheManager class (singleton) uses, as parameter, an instance of the existing MemoryCache class and wraps around a few helpful methods to deal with supplementary stuff such as object life cycle within my custom cache.

That Manager deals with a simple CachableObject that takes three variables :

  • object
  • DateTime
  • int (duration)

In summary, my custom cache Manager stores objects for a limited amount of time in order to protect my database from frequent big queries.

Lately, I tried to :

  • Got back an object from the cache (ie : stored under the key -MyList)
  • Casted it back to a list of complexe objects
  • Translated the content of some properties for each complexe objects
  • Stored again the freshly translated list of objects within the cache, (under another key -MyTranslatedList)

The problem :
During my testing, it appeared to me that both lists stored in the cache (raw and translated one) were refering to the same underlying objects. Therefore, once translated, those objects were actually translated in both lists.
Since each list only has references to the objects, that's a perfectly normal behavior and a silly mistake from me.

The question :
As you can easily guess now, I would like to protect myself and other users of my singleton for that kind of mistakes.

I would like to insert (or store or get) any kind of object (or list of complexe objects) so they cannot be altered by anybody getting them through the cache. I would like the data within my cache to be readonly (and deeply readonly) to avoid having that kind of problem. I want anybody to have to create a deep copy (or even better, to get one) before starting to use the data stored within the cache.

What I tried so far :
I tried to make the object readonly. It didn't work as expected.

Since I'm often storing list of complexe objects, I've found the AsReadOnly method that return a IReadOnlyCollection, but while this prevents me from altering the list (add, remove) it doesn't protect the objects that are within the list.

I hope my explanation is somewhat understandable :) Is there a neat way of dealing with that kind of situation ?

4

1 回答 1

0

我将创建一个属性为只读的类:

class ReadonlyClass
{
    private string p1;
    private int p2;

    public ReadonlyClass(string property1, int property2)
    {
        p1 = property1;
        p2 = property2;
    }

    public string Property1
    {
        get { return p1; }
    }

    public int Property2
    {
        get { return p2; }
    }
}

如果属性是对象/其他类,您应该实现一个返回对象副本的克隆函数。上述类的克隆函数如下所示:

    public ReadonlyClass clone()
    {
        return new ReadonlyClass(p1, p2);
    }

最好的问候汉斯·米林...

于 2015-03-12T09:17:32.710 回答