使用反射来创建由“类型”的内容表示的对象。目的
我正在使用反射来通过这样的字符串查找类型...
Type currentType = Type.GetType(typeName);
然后我可以获得该类型的属性列表,如下所示...
var props = currentType.GetProperties();
如何实例化这种类型的新对象,然后开始为其赋值该对象的属性基于 props 列表中的属性列表?
I am using reflection to find a type by a string like this...
Type currentType = Type.GetType(typeName);
I then am able to get a list of properties for that type like this...
var props = currentType.GetProperties();
How do I instantiate a new object of this type and then start assigning values to the properties of that object based on the list of properties in the props list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用您已有的价值观...
Using the values you already have...
使用以下方式实例化
currentType
并使用以下方式分配属性值:
其中
propInfo
是props
中的PropertyInfo
实例,并且 < code>propValue 是要分配给属性的对象。编辑:
我总是倾向于使用更详细的
SetValue
重载,因为我过去在短重载方面遇到过问题,但是propInfo.SetValue(newInst, propValue, null);
propInfo.SetValue(newInst, propValue, null); 也可能有效。Instantiate the
currentType
with:and assign property values with:
Where
propInfo
is thePropertyInfo
instance from yourprops
andpropValue
is the object you want to assign to the property.EDIT:
I always lean towards using the more verbose
SetValue
overload because I've had problems with the short one in the past, butpropInfo.SetValue(newInst, propValue, null);
might work as well.