[英]How to create an object instance of class with internal constructor via reflection?
Example: 例:
class Program
{
static void Main(string[] args)
{
var myClass = Activator.CreateInstance(typeof(MyClass));
}
}
public class MyClass
{
internal MyClass()
{
}
}
Exception: 例外:
System.MissingMethodException
system.missingMethodException而
No parameterless constructor defined for this object.
没有为此对象定义的无参数构造函数。
Solution: 解:
var myClass = Activator.CreateInstance(typeof(MyClass), nonPublic:true);
I cannot understand, why I cannot create an instance inside the assembly with internal constructor. 我无法理解,为什么我无法使用内部构造函数在程序集内创建实例。 This constructor should be available inside the execution assembly.
此构造函数应该在执行程序集中可用。 It should work like public for this assembly.
对于这个程序集,它应该像public一样工作。
It is not that impossible. 这不是不可能的。 you've to tell it is not a public.
你要告诉它不是一个公众。
var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic
The constructor inside your MyClass is Internal try to change to public MyClass中的构造函数是Internal尝试更改为public
public class MyClass
{
public MyClass()
{
}
}
or 要么
Pass true to CreateInstance 将true传递给CreateInstance
var myClass = Activator.CreateInstance(typeof(MyClass),true );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.