如何在实例化对象上使用反射调用方法?

H4m*_*ead 1 c# reflection

我有一些基础对象"Car","dog","cat"他们实现了一个接口"IGWUIElement".我有一个这些接口的列表:列出myList.

在运行时,我循环遍历我的元素列表,并通过检查类的名称(使用反射)我需要填充它们的属性 - 这不是界面的一部分).我有一个xml文档描述了我应该分配给它们的属性和值.这是我的界面实例化.

IGWUIElement newUIElement = (IGWUIElement)Activator.CreateInstance(result);
Run Code Online (Sandbox Code Playgroud)

如何使用特定值从名称中调用属性(请注意,数据类型仅限于int和string).每个对象都有不同的属性.

希望这有道理......

/ H4mm3r

小智 5

使用PropertyInfo.SetValue()

PropertyInfo piInstance = typeof(IGWUIElement).GetProperty("property_name");
piInstance.SetValue(newUIElement, value, null);
Run Code Online (Sandbox Code Playgroud)

更多关于msdn.