Instantiating Internal class with private constructor

前端 未结 5 981
挽巷
挽巷 2020-11-30 08:25

I am trying to use reflection to create instance of a class. But it is sealed internal and has private constructor. I wonder how can i initiaise it and as its part of framew

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 09:10

    If it's internal to an assembly that is not yours and the constructor is marked as private, the author of the assembly is trying very hard to keep you from creating the object.

    The below is really evil as you're relying on non-public classes and methods which could change on you without advance notice.

    Added: System.ServiceModel.Channels.SelfSignedCertificate is the internal class I am trying to use

    Do not do this. The framework could change under you in the blink of an eye ruining your code and all of your hard work.

    That said, you could do this:

    MethodInfo method = Type.GetType(assemblyQualifiedName).GetMethod("Create");
    ABC o = (ABC)method.Invoke(null, new[] { "test" });
    

    This invokes the static method Create. Another option is

    MethodInfo method = Type.GetType(assemblyQualifiedName).GetConstructor(
                            BindingFlags.NonPublic | BindingFlags.Instance,
                            null,
                            new[] { typeof(string) },
                            null
                        );
    ABC o = (ABC)method.Invoke(new[] { "test" });
    

    which uses reflection to load the constructor that accepts a string as a parameter.

    An easy way to get the assembly-qualified name is

    string name = typeof(somePublicType).Assembly.GetType("Namespace.ABC");
    

    where somePublicType is a type that is public and in the same assembly as ABC.

提交回复
热议问题