DWQA QuestionsCategory: ProgramC ා how to instantiate a class with a strange singleton pattern
SSS turbidity current asked 4 months ago

How can a singleton like qqauthapi be instantiated

public class Singleton<T>
    {
        protected static T sInstance = New();

        protected Singleton() { }

        public static T Instance
        {
            get { return sInstance; }
        }

        private static T New()
        {
            Type t = typeof(T);
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.OptionalParamBinding;
            return (T)Activator.CreateInstance(t, flags, null, null, CultureInfo.CurrentCulture);
        }
    }
public class QQAuthApi : Singleton<QQsAuthApi>
    {
        public ThirdUserInfo Login(string qqsSid)
        {
            return AccountUtil.QQSidLogin(qqsSid);
        }
    }
2 Answers
Wood by answered 4 months ago

Without instantiation, it can be used directly QQAuthApi.Instance

Meat rabbit answered 4 months ago

Qqauthapi inherits from singleton and specifies the generic type as its own. The method of getting instance under singleton is new (), and the instance obtained by new in get of instance. Therefore, you can use

var api = QQAuthApi.Instance;

To get an instance of it.