如何通过反射使用内部构造函数创建类的对象实例? [英] How to create an object instance of class with internal constructor via reflection?

查看:161
本文介绍了如何通过反射使用内部构造函数创建类的对象实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

class Program
{
    static void Main(string[] args)
    {
        var myClass = Activator.CreateInstance(typeof(MyClass));
    }
}

public class MyClass
{
    internal MyClass()
    {
    }
}

例外:

System.MissingMethodException

没有为此对象定义无参数的构造函数.

No parameterless constructor defined for this object.

解决方案:

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.

推荐答案

并非没有可能.您必须告诉它不是公众.

It is not that impossible. you've to tell it is not a public.

var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic

这篇关于如何通过反射使用内部构造函数创建类的对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆