Activator.CreateInstance with private sealed class

后端 未结 4 2253
野性不改
野性不改 2020-12-17 17:30

I\'m trying to new up a LocalCommand instance which is a private class of System.Data.SqlClient.SqlCommandSet. I seem to be able to grab the type information just fine:

4条回答
  •  时光说笑
    2020-12-17 17:51

    Trick is to make sure to use the right CreateInstance overload:

    // WRONG
    ... Activator.CreateInstance(
           type,
           BindingFlags.Instance
           | BindingFlags.NonPublic
        );
    

    This calls the params overload, which will default to Instance | Public | CreateInstance, and your binding flags will be passed as arguments to the constructor, giving the vague MissingMethodException.

    Also, use Instance | Public | NonPublic if you aren't sure of the visibility of the constructor:

    // right
    ... Activator.CreateInstance(
           type,
           BindingFlags.Instance
           | BindingFlags.Public
           | BindingFlags.NonPublic,
           null,
           new object[] { }, // or your actual constructor arguments
           null
        );
    

提交回复
热议问题