简体   繁体   English

如何使用反射添加到集合-C#

[英]How to add to collection using reflection - C#

I am new to C# and reflection in specific and I am trying to solve a very specific problem. 我是C#的新手,并且是具体的反思,我正在尝试解决一个非常具体的问题。 I want to implement the following code using reflection (since in some machines the System.Windows.Forms.DataVisualization.dlls might not be present, in those case i will skip generating charts). 我想使用反射实现以下代码(由于在某些计算机上可能不存在System.Windows.Forms.DataVisualization.dll,因此在这种情况下,我将跳过生成图表)。

Chart chart1 = new Chart();
string chartTitle = "Chart Title";
chart1.Titles.Add(chartTitle);

I figured out how to load a dll, get its class type, get/set its static/non-static properties, use constructors to create objects etc via Reflections. 我想出了如何加载dll,获取其类类型,获取/设置其静态/非静态属性,使用构造函数通过反射创建对象等的方法。 But I am quite lost about how to invoke "add" method on a collection. 但是我对如何在集合上调用“ add”方法一无所知。 Say, i have object Chart1 and chartTitle via Reflection, how do i implement the 3rd line of code using Reflection. 说,我通过反射拥有对象Chart1和chartTitle,如何使用反射实现代码的第三行。

Appreciate your help. 感谢您的帮助。 Thanks in advance. 提前致谢。

Green Apple 青苹果

If you already have the object chart1 instance then you can use 如果您已经有object chart1实例,则可以使用

object titles = typeof(chart1).GetProperty("Titles").GetValue(chart1);

or 要么

object titles = chart1.GetType().GetProperty("Titles").GetValue(chart1);

to get the chart1.Titles instance. 获取chart1.Titles实例。

Then use titles.GetMethod("Add").Invoke(titles, chartTitle); 然后使用titles.GetMethod("Add").Invoke(titles, chartTitle); to add the new title. 添加新标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM