Activator.CreateInstance with private sealed class

后端 未结 4 2367
野性不改
野性不改 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:39

    I got it to work this way:

    using System;
    using System.Reflection;
    
    class Test
    {
        public String X { get; set; }
    
        Test(String x)
        {
            this.X = x;
        }
    }
    
    class Program
    {
        static void Main()
        {
            Type type = typeof(Test);
    
            ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, 
                null, new Type[] { typeof(String) }, null);
    
            Object o = c.Invoke(new Object[] { "foo" });
        }
    }
    

    The trick was to go after the constructor specifically with GetConstructor rather then trying to find it in the results of GetConstructors. Go figure.

提交回复
热议问题