C# Singleton

Generics mint fogalom létezik a .net-ben. És ez jó. Gondoltam csinálok egy singleton ősosztályt mert az legalább olyan jó mint a generics.

   public abstract class Singleton<T> System.Object, new()
    {
        private static T _instance;

        public static T get()
        {
            if (_instance == null)
            {
                _instance=new T();
            }
            return _instance;
        }
    }

Öröm boldogság, gondoltam. De a fordító nem örült, és ezt mondta:

Error 1 Constraint cannot be special class ‘object’

Ejnye. Megnéztem a helpet.

Compiler Error CS0702
The following types may not be used as constraints: System.Array, System.Delegate, System.Enum, or System.ValueType.

Szerencsére, mint a Microsoft termékeknél általában, mindig van egy alternatív megoldás.

    public abstract class Singleton<T>
    {
        private static T _instance;

        public static T get()
        {
            if (_instance == null)
            {
                _instance = System.Activator.CreateInstance<T>();
            }
            return _instance;
        }
    }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.