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

编程入门 行业动态 更新时间:2024-10-27 06:33:38
本文介绍了如何通过反射使用内部构造函数创建类的对象实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

示例:

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

更多推荐

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

本文发布于:2023-11-04 10:09:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557641.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   函数   实例   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!