简体   繁体   English

如何通过反射使用内部构造函数创建类的对象实例?

[英]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.

相关问题 如何使用Reflection创建带有参数的内部构造函数的实例? - How to create an instance of the internal constructor with parameters using Reflection? 如果类的构造函数是内部的,如何创建对象 - How to create the object if constructor for the class is internal Reflection C#:创建一个没有默认构造函数的对象实例 - Reflection C#: Create instance of an object which has no default constructor 如何使用反射创建以接口为构造函数参数的类实例? - How to create an instance of class that takes interface as its constructor parameter using reflection? C#反射-如果类没有默认构造函数,如何创建PrivateObject对象或PrivateType对象? - C# Reflection - How to create PrivateObject object or PrivateType object if class does not have default constructor? 通过反射在c#中创建类的实例 - Create instance from class in c# via reflection 反思:如何通过 PropertyInfo 获取类对象 - Reflection: How to get the class object via PropertyInfo 使用反射在内部类中使用参数实例化构造函数 - Instantiating a constructor with parameters in an internal class with reflection Reflection Emit创建类实例 - Reflection Emit to create class instance 如何在不使用反射的情况下从类名称创建类的实例? - How to create instance of a class from class name without using reflection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM