I am new to C# and reflection in specific and I am trying to solve a very specific problem. 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).
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. But I am quite lost about how to invoke "add" method on a collection. Say, i have object Chart1 and chartTitle via Reflection, how do i implement the 3rd line of code using Reflection.
Appreciate your help. Thanks in advance.
Green Apple
If you already have the object chart1
instance then you can use
object titles = typeof(chart1).GetProperty("Titles").GetValue(chart1);
or
object titles = chart1.GetType().GetProperty("Titles").GetValue(chart1);
to get the chart1.Titles
instance.
Then use titles.GetMethod("Add").Invoke(titles, chartTitle);
to add the new title.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.