How to instantiate an object with a private constructor in C#?

后端 未结 4 431
盖世英雄少女心
盖世英雄少女心 2020-12-03 09:41

I definitely remember seeing somewhere an example of doing so using reflection or something. It was something that had to do with SqlParameterCollection which i

4条回答
  •  醉话见心
    2020-12-03 10:24

    It will also help if your Type is private or internal:

     public static object CreatePrivateClassInstance(string typeName, object[] parameters)
        {
            Type type = AppDomain.CurrentDomain.GetAssemblies().
                     SelectMany(assembly => assembly.GetTypes()).FirstOrDefault(t => t.Name == typeName);
            return type.GetConstructors()[0].Invoke(parameters);
        }
    

提交回复
热议问题