Activator.CreateInstance(string) and Activator.CreateInstance() difference

前端 未结 3 500
借酒劲吻你
借酒劲吻你 2020-12-14 22:39

No, this is not a question about generics.

I have a Factory pattern with several classes with internal constructors (I don\'t want them being instantiated if not thr

相关标签:
3条回答
  • 2020-12-14 22:56

    besides Activator.CreateInstance(typeof(T), true) to work, T should have default constructor

    0 讨论(0)
  • 2020-12-14 23:08

    To get around this, couldnt you just alter your usage as such:

    public class GenericFactory<T> where T : MyAbstractType
    {
        public static T GetInstance()
        {
            return Activator.CreateInstance(typeof(T), true);
        }
    }
    

    Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.

    0 讨论(0)
  • 2020-12-14 23:13

    If you absolutely require that the constructor be private you can try something like this:

    public abstract class GenericFactory<T> where T : MyAbstractType
    {
        public static T GetInstance()
        {
            return (T)Activator.CreateInstance(typeof(T), true);
        }
    }
    

    Otherwise you're best off adding the new constraint and going that route:

    public abstract class GenericFactory<T> where T : MyAbstractType, new()
    {
        public static T GetInstance()
        {
            return new T;
        }
    }
    

    You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right?

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