简体   繁体   中英

Accessing the constructor by using Reflection

Assume the class is public and and the constructor is internal like as

Public class A
{
    private string text;

    internal A(string submittedText);

    public string StrText { get; }
}

In this case how could I Access the constructor by using Reflection. What I have done so far

Type[] pTypes = new Type[1];

pTypes[0] = typeof(object);

object[] argList = new object[1];

argList[0] = "Some Text";


ConstructorInfo c = typeof(A).GetConstructor
                (BindingFlags.NonPublic |
                 BindingFlags.Instance,
                 null,
                 pTypes,
                 null);


A foo = (A)c.Invoke(BindingFlags.NonPublic,
                    null,
                    argList,
                    Application.CurrentCulture);

But it shows an error. Any Suggestions

I think the error might casued by the GetConstructor, you passed in Object type instead of String type.

var ctr = typeof(A).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);

btw, if the type A itself is internal, and you know public Type B and A in the same assembly, you can try:

Type typeA = typeof(B).Assembly.GetType("Namespace.AssemblyName.A", false);
var ctr = typeA.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);

Try this:

Type type = typeof(A);

            Type[] argTypes = new Type[] { typeof(String) };

            ConstructorInfo cInfo = type.GetConstructor(argTypes);

            object[] argVals = new object[] { "Some string" };
            Ap = (A)cInfo.Invoke(argVals);

I got help from this site:

http://www.java2s.com/Code/CSharp/Reflection/CallGetConstructortogettheconstructor.htm

I just tried it on a sample console app, where I had an internal class and it worked.

namespace ConsoleApplication1
{
    internal class Person
    {
        public Person(string name)
        {
            Name = name;
        }

        public string Name { get; set; }
    }
}

public static void Main()
        {

            Type type = typeof(Person);

            Type[] argTypes = new Type[] { typeof(String) };

            ConstructorInfo cInfo = type.GetConstructor(argTypes);

            object[] argVals = new object[] { "Some string" };
            Person p = (Person)cInfo.Invoke(argVals);
        }

Argument type in the constructor is string, not object. So maybe like this:

pTypes[0] = typeof(string);

您应该使用Activator.CreateInstance

you can use object o1 = Activator.CreateInstance(typeof (myclass), true); for creating a instance. no need to go through that complicated code for creating instances in the same method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM