Prevent a class containing static instances of it created in C #

Is there a way to prevent the creation of a class with static instances created in C #. I do not think there is, but it can be useful. For example, only some attributes to prevent it.

something like that

[NoStaticInstances]
public class MyClass {
}

so that

public static MyClass _myClass;

will lead to an error?

+3
source share
5 answers

What you can do is the following:

public class MyClass
{
    public MyClass()
    {
#if DEBUG // Only run in debug mode, because of performance.
        StackTrace trace = new StackTrace();

        var callingMethod = trace.GetFrames()[1].GetMethod();

        if (callingMethod.IsStatic && 
            callingMethod.Name == ".cctor")
        {
            throw new InvalidOperationException(
                "You naughty boy!");
        }
#endif
    }
}

Static fields will "normally" be created by static constructors. What the above code does, it looks at the calling method to see if it is a static constructor, and if that happens throw an exception.

, , , . , , .

+3

, " " - , . , , , - - .

, ... , ?

class Test
{
    static object foo;

    static void Main()
    {
        MyClass bar = new MyClass();
        foo = bar;
    }
}

, ? , :

class Test
{
    static object foo;

    static void Main()
    {
        MyClass bar = new MyClass();
        object tmp = bar;
        foo = tmp;
    }
}

, , , . , ?

+9

.

,

static object something = new YourClass();
+2

There is really no language or compiler function that supports this.

+1
source

No, there is no way to determine the scope or lifetime of object references in C #.

0
source

All Articles