开发者

Referencing a static class from an array?

开发者 https://www.devze.com 2023-01-31 09:05 出处:网络
I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references t

I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way th开发者_如何学Ce numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

Map.GetBlock(x,y).AccessToStaticClassMembers;

So, how would I go about this?


I'm not really sure what you want. But it sounds like you're trying to ensure that there is only one instance in memory for each number. If that's the case, what's wrong with something like this:

static public class ObjectMapping
{
    static Dictionary<int, object> dictionary = new Dictionary<int, object>();

    static public object GetObjectForNumber(int x)
    {
        object o;
        if (!dictionary.ContainsKey(x))
        {
            o = CreateObjectForNumberTheFirstTime(x);
            dictionary.Add(x, o);
            return o;
        }
        return dictionary[x];
    }
}

Of course, I left out things such as thread safety and creation of the objects in the first access, for you to do on your own.


Why make it static? This looks more like overrides of some abstract method or implementations of some interface method, if I got you correctly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号