Best way to prevent a class from being Instantiated?

后端 未结 5 1955
北海茫月
北海茫月 2020-12-14 20:20

I need to know how to prevent a class from being Instantiated in .net?

I know few methods like making the class Abstract and Static.

Is there any more way to

5条回答
  •  一整个雨季
    2020-12-14 21:19

    If the question is:

    How can you make your class not be instanced without having your class be static or abstract?

    Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:

    public sealed class myClass
    {
        private static readonly Lazy lazyInstance = 
            new Lazy(() => new myClass());
    
        public static Instance
        {
            get
            {
                return lazyInstance.Value;
            }
        }
    
        private myClass()
        {
            // constructor logic here
        }
    }
    

    The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.

    Without .NET4 you can still implement the singleton pattern, for example:

    private static readonly myClass instance = new myClass();
    
    public static Instance
    {
        get
        {
            return instance;
        }
    }
    
    // rest of code remains the same
    

    Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.

    In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.

    As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.

    Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.

提交回复
热议问题