c# - Compact Framework - 如何动态创建没有默认构造函数的类型?

标签 c# reflection compact-framework

我使用的是.NET CF 3.5。我想要创建的类型没有默认构造函数,因此我想将字符串传递给重载的构造函数。我该怎么做?

代码:

Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type

string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException

最佳答案

MyObj o = null;
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");

ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });
if(ctor != null)
   o = ctor.Invoke(new object[] { s });

关于c# - Compact Framework - 如何动态创建没有默认构造函数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436/

相关文章:

c# - 以编程方式删除 Windows Mobile 设备上的电子邮件和 SMS

c# - 如何使用 C# 检查一个类是否实现了泛型并与泛型接口(interface)?

c# - 单击按钮后停止启用单选按钮?

c# - 变量中 Linq 查询的 Lambda 表达式

c# - 如何在 ASP.NET C# 中获取网页源代码?

reflection - 不能在用反射制作的 slice 上使用范围,然后传递 json.Unmarshal

reflection - 如何通过反射使用 Kotlin 对象

java - 如何使用默认访问(或包默认)访问构造函数

从紧凑框架调用 WCF 服务

compact-framework - 使用 .net Compact Framework 编写的应用程序可以自行重启吗?