Best way to prevent a class from being Instantiated?

后端 未结 5 1942
北海茫月
北海茫月 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 20:56

    Mark the constructor(s) private, protected or if in used from another assembly, internal

    0 讨论(0)
  • 2020-12-14 21:05

    Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.

    Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).

    Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)

    See MSDN for more information about static classes.

    0 讨论(0)
  • 2020-12-14 21:15

    Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...

    More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).

    0 讨论(0)
  • 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<myClass> lazyInstance = 
            new Lazy<myClass>(() => 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.

    0 讨论(0)
  • 2020-12-14 21:21

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

    Your question is not clear.

    Do you mean instantiated at runtime? Make the class abstract or static.

    Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.

    So, which do you mean?

    0 讨论(0)
提交回复
热议问题