简体   繁体   中英

Design pattern for properties and static constructor

I have a base class with static properties and a static constructor. Now when I create a derived instance I want those properties to be isolated to that instance (non-static). How can I solve this?

Updated answer to match updated question.

To access the static properties through the instance class you could simply use something like:

class SomeClass
{
    private static string staticFoo;

    public string Foo
    {
        get { return SomeClass.staticFoo; }
    }
}

Static constructors however are something different. You cannot call them manually, and they are called once automatically when the first instance is created or static member is referenced. More info on static constructors on MSDN.

Updated for comment:

I think this is the closest to what you want.

class SomeClass
{
    private static string staticFoo;

    private string instanceFoo;

    public SomeClass()
    {
        instanceFoo = staticFoo; // Assign the instance variable.
    }

    public static string StaticFoo // Static property.
    {
        get { return staticFoo; }
    }

    public string Foo // Instance property.
    {
        get { return instanceFoo; }
    }
}

The best would be for you to change the base class to not have static properties. If you want them to be instance specific, don't make them static.

If you cannot change the base class you can create new properties in your subclass and copy the values of the static properties of the base class to your non-static properties in the subclass constructor, and then use the subclass properties instead of the static base class properties.

However if you have existing code you cannot change that is using the base class static properties, and you are hoping to somehow coerce the static properties to no longer be static, then you are out of luck.

Ok answering my own question. So I managed to solve it this way:

public abstract class IntegrationTestBase
{
    private static bool _constructed;

    protected IntegrationTestBase()
    {
        if (_constructed)
        {
            lock (Lock)
            {
                AssignNonStaticProperties();
            }

            return;
        }

        _constructed = true;

        // Do the stuff which was originally in the static constructor, runs only once
        ...
    }
}

Doing this I also had to make a bunch of methods non-static. I also had some problems with [ClassInitialize] which must be used on a static method. So I changed these to a default constructor with a _constructed bool aswell.

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