[英]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. 我认为该错误可能是由GetConstructor引起的,您传入了Object类型而不是String类型。
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: 顺便说一句,如果类型A本身是内部的,并且您在同一程序集中知道公共类型B和A,则可以尝试:
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 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);
您可以使用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. 无需通过复杂的代码即可使用同一方法创建实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.