简体   繁体   中英

How do you Invoke methods on ArrayList using its FieldInfo (Reflection)

In my code, I declare one ArrayList within a ParentClass

public class ParentClass {
...
public ArrayList hybridElem; 
...

and then using Reflection that runs off the ParentClass, I am able to successfully obtain FieldInfo for this ArrayList @ runtime.

Using that FieldInfo, I want to be able to add or read elements from the hybridElem. I am able to obtain all relevant PropertyInfo of ArrayList such as .Item, .Count, .ToArray etc etc ... and also obtain getters and setters for these properties.

Unfortunately, none of them are being successfully invoked because MethodInfo.Invoke expects Object reference to ArrayList

Any Solutions?

You can do it easily enough. However, as the comments rightfully stated, I suggest you to switch from ArrayList to a generic collection.

var instance = new ParentClass();
var fieldInfo = instance.GetType().GetProperty("MyList");
var arrayList = fieldInfo.GetValue(instance) as ArrayList;
var count = arrayList.Count;

With:

public class ParentClass
{
    public ArrayList MyList { get; set; }

    public ParentClass()
    {
        MyList = new ArrayList();
    }
}

Alternatively, to adapt it to your class which uses a field (assuming that said field is initialized somewhere):

var instance = new ParentClass();
var fieldInfo = instance.GetType().GetField("hybridElem");
var arrayList = fieldInfo.GetValue(instance) as ArrayList;
var count = arrayList.Count;

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.

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