473,383 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Using reflection modify List<int> type class member...

Hi

I am trying to modify class instance members using reflection. I am having problem when trying to add/remove/display elements related to List<int> member. Following is the code.

Expand|Select|Wrap|Line Numbers
  1.     class TestClass
  2.     {
  3.         public int i = 0;
  4.  
  5.         public int IValue
  6.         {
  7.             get
  8.             {
  9.                 return i;
  10.             }
  11.             set
  12.             {
  13.                 i = value;
  14.             }
  15.  
  16.         }
  17.         public List<int> m_intList = new List<int>();
  18.     }
  19.     class Program
  20.     {
  21.         static void Main(string[] args)
  22.         {
  23.             TestClass tcObject = new TestClass();
  24.             tcObject.i = 1;
  25.             tcObject.m_intList.Add(1);
  26.             tcObject.m_intList.Add(2);
  27.  
  28.             // Following code modifies the field "I".
  29.             {
  30.                 FieldInfo fieldInfo = tcObject.GetType().
  31.                                         GetField(
  32.                                         "i",
  33.                                         BindingFlags.Static |
  34.                                         BindingFlags.Instance |
  35.                                         BindingFlags.NonPublic |
  36.                                         BindingFlags.Public);
  37.  
  38.                 fieldInfo.SetValue(tcObject, 2);
  39.  
  40.                 System.Console.WriteLine("I value '{0}'", fieldInfo.GetValue(tcObject));
  41.             }
  42.  
  43.             // Following code modifies the IValue property.
  44.             {
  45.                 PropertyInfo propertyInfo = tcObject.GetType().
  46.                                         GetProperty(
  47.                                         "IValue",
  48.                                         BindingFlags.Static |
  49.                                     BindingFlags.Instance |
  50.                                     BindingFlags.NonPublic |
  51.                                     BindingFlags.Public);
  52.  
  53.                 MethodInfo propertySetMethodInfo =
  54.                                 propertyInfo.GetSetMethod(true);
  55.  
  56.                 propertySetMethodInfo.Invoke(tcObject, new Object[] { 3 });
  57.  
  58.                 System.Console.WriteLine("Property IValue '{0}'", tcObject.i);
  59.             }
  60.  
  61.             // Following is the actual problem I am having. I would like to add
  62.             // elements to the List member m_intList.
  63.             {
  64.                 FieldInfo fieldInfo = tcObject.GetType().
  65.                                         GetField(
  66.                                         "m_intList",
  67.                                         BindingFlags.Static |
  68.                                         BindingFlags.Instance |
  69.                                         BindingFlags.NonPublic |
  70.                                         BindingFlags.Public);
  71.  
  72.                 // HOW do I add elements to m_intList using the fieldInfo object.
  73.                 // I am trying to use reflection to modify values for the members.
  74.  
  75.                 foreach (int intItem in tcObject.m_intList)
  76.                 {
  77.                     System.Console.WriteLine("List Item value '{0}'", intItem);
  78.                 }
  79.             }
  80.         }
  81.     }
  82.  
Thanks
Chandra
Oct 16 '08 #1
6 2911
In my actual application I do not know the type i.e. whether it is List<int> or List<String> etc

I will just have the tcObject. From the tcOBject I will get FieldInfo object corresponding to m_intList. Using this FieldINfo, I should be able to add or remove elements.
Oct 16 '08 #2
At compile time I do not know whether the type is List<int> or List<String>. At runtime I should interpret it from the fieldInfo.FieldType.
Oct 16 '08 #3
I even tried the following code
Expand|Select|Wrap|Line Numbers
  1.                 MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add"); 
  2.                 addMethodInfo.Invoke(tcObject, new Object[] { 5 }); 
But the above code gives me error "Unhandled Exception: System.Reflection.TargetException: Object does not match target type." when executing the "invoke"
Oct 16 '08 #4
Plater
7,872 Expert 4TB
If you wanted to add the int value 1234, I would think you would invoke the Add member with a new object(){1234} as the parameter?

For example:
Expand|Select|Wrap|Line Numbers
  1. List<int> myList = new List<int>();
  2. myList.Add(98);
  3. Type tt = myList.GetType();
  4. tt.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, myList, new object[] { 1234 });
  5. MessageBox.Show(fred.Count.ToString());
  6.  
You could probably do something similar with the MemberInfo stuff?
Oct 16 '08 #5
I do not have access to m_myList, I have access to only "tcObject" instance of the class. This instance has the member m_myList.
Oct 16 '08 #6
Hello everyone, thanks for your help. I was able to find the solution for my requirement. Following is the code

Expand|Select|Wrap|Line Numbers
  1.     class ListElement
  2.     {
  3.         public ListElement()
  4.         {
  5.             m_element = 0;
  6.         }
  7.  
  8.         public ListElement(int element)
  9.         {
  10.             m_element = 1;
  11.         }
  12.  
  13.         public int m_element;
  14.     }
  15.  
  16.     class TestClass
  17.     {
  18.         public int i = 0;
  19.  
  20.         public int IValue
  21.         {
  22.             get
  23.             {
  24.                 return i;
  25.             }
  26.             set
  27.             {
  28.                 i = value;
  29.             }
  30.  
  31.         }
  32.         public List<int> m_intList = new List<int>();
  33.         public List<ListElement> m_lstElement = new List<ListElement>();
  34.     }
  35.     class Program
  36.     {
  37.         static void Main(string[] args)
  38.         {
  39.             TestClass tcObject = new TestClass();
  40.             tcObject.i = 1;
  41.             tcObject.m_intList.Add(1);
  42.             tcObject.m_intList.Add(2);
  43.             tcObject.m_lstElement.Add(new ListElement(1));
  44.  
  45.             // Following code modifies the field "I".
  46.             {
  47.                 FieldInfo fieldInfo = tcObject.GetType().
  48.                                         GetField(
  49.                                         "i",
  50.                                         BindingFlags.Static |
  51.                                         BindingFlags.Instance |
  52.                                         BindingFlags.NonPublic |
  53.                                         BindingFlags.Public);
  54.  
  55.                 fieldInfo.SetValue(tcObject, 2);
  56.  
  57.                 System.Console.WriteLine("I value '{0}'", fieldInfo.GetValue(tcObject));
  58.             }
  59.  
  60.             // Following code modifies the IValue property.
  61.             {
  62.                 PropertyInfo propertyInfo = tcObject.GetType().
  63.                                         GetProperty(
  64.                                         "IValue",
  65.                                         BindingFlags.Static |
  66.                                     BindingFlags.Instance |
  67.                                     BindingFlags.NonPublic |
  68.                                     BindingFlags.Public);
  69.  
  70.                 MethodInfo propertySetMethodInfo =
  71.                                 propertyInfo.GetSetMethod(true);
  72.  
  73.                 propertySetMethodInfo.Invoke(tcObject, new Object[] { 3 });
  74.  
  75.                 System.Console.WriteLine("Property IValue '{0}'", tcObject.i);
  76.             }
  77.  
  78.             {
  79.                 FieldInfo fieldInfo = tcObject.GetType().
  80.                                         GetField(
  81.                                         "m_intList",
  82.                                         BindingFlags.Static |
  83.                                         BindingFlags.Instance |
  84.                                         BindingFlags.NonPublic |
  85.                                         BindingFlags.Public);
  86.  
  87.                 MemberInfo[] listMemberInfoArray = tcObject.GetType().GetMember("m_intList");
  88.                 MemberInfo listMemberInfo = listMemberInfoArray[0];
  89.                 MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add");
  90.                 object[] elementValue = { 5 };
  91.                 addMethodInfo.Invoke(fieldInfo.GetValue(tcObject), elementValue);
  92.  
  93.                 foreach(int currElement in tcObject.m_intList)
  94.                 {
  95.                     System.Console.WriteLine("INt List element {0}", currElement);
  96.                 }
  97.  
  98.                 Console.WriteLine();
  99.             }
  100.  
  101.             {
  102.                 FieldInfo fieldInfo = tcObject.GetType().
  103.                                         GetField(
  104.                                         "m_lstElement",
  105.                                         BindingFlags.Static |
  106.                                         BindingFlags.Instance |
  107.                                         BindingFlags.NonPublic |
  108.                                         BindingFlags.Public);
  109.  
  110.                 MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add");
  111.                 Object listElementObject = Activator.CreateInstance(fieldInfo.
  112.                                                             FieldType.
  113.                                                             GetGenericArguments()[0]);
  114.  
  115.                 FieldInfo listElementFieldInfo = listElementObject.GetType().
  116.                                         GetField(
  117.                                         "m_element",
  118.                                         BindingFlags.Static |
  119.                                         BindingFlags.Instance |
  120.                                         BindingFlags.NonPublic |
  121.                                         BindingFlags.Public);
  122.  
  123.                 listElementFieldInfo.SetValue(listElementObject, 2);
  124.  
  125.                 object[] elementValue = { listElementObject };
  126.                 addMethodInfo.Invoke(fieldInfo.GetValue(tcObject), elementValue);
  127.  
  128.  
  129.                 foreach (ListElement currListElement in tcObject.m_lstElement)
  130.                 {
  131.                     System.Console.WriteLine("List Item value '{0}'", currListElement.m_element);
  132.                 }
  133.             }
  134.  
  135.         }
  136.     }
  137.  
Oct 16 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: deathtospam | last post by:
Is it possible to Databind to a strongly-typed list of integers (List<int>) ? I want to use <%# Databinder.Eval(Container.DataItem, "XXX") %inside a Repeater control in my ASPX page, but I don't...
2
by: per9000 | last post by:
Hi, *background* I want a class containing an int (a list of sets of integer). This should be hidden for the user and he/she should be able to insert his/her favourite data structure so to be a...
8
by: per9000 | last post by:
Hi, I wanted to test to compile an application I build for .NET 2.0 in with the 1.1 C# compiler. I encountered difficulties since I had a List<myClass>. I found a list of what is new in .NET 2.0...
1
by: Monty | last post by:
I have a Usercontrol with a public property List<intLinks List <intLinks= new List<int>(); public List<intLinkLabels { get { return Links; } set { Links = value; } }
10
by: arnuld | last post by:
It is quite an ugly hack but it is all I am able to come up with for now :-( and it does the requires work. I want to improve the program, I know you people have much better ideas ;-) /* C++...
10
by: arnuld | last post by:
WANTED: /* C++ Primer - 4/e * * Exercise: 9.26 * STATEMENT * Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to...
2
by: =?Utf-8?B?QW50?= | last post by:
Hi, I found in MSDN some sample code: List<intnumQry = ...etc I couldn't find any info in MSDN on List or <intthough. Does anybody know what this is & in which namespace it belongs in? ...
0
by: DR | last post by:
System.Collections.Generic.List<intmyList = new System.Collections.Generic.List<int>(100); Does this preallocate 100 integers? Also, is there any way to preallocate an array of objects all at...
15
by: hsachdevah | last post by:
Hello, I am trying to create a dictionary item with its key as list type and value as custom object type. It gives me a error "An item with the same key has already been added." Here is my code:...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.