Wednesday, March 16, 2011

How to access the Index Of A Generic.List By Reflection??

ok, ive a class and i pass an object as property.

the object that i pass is a List<X>

in my class im trying to access the Object index by reflection BUT I CAN'T!!!

Example:

this class works i just wrote down the part i want to show you and i need help.

class MyClass
{
    private object _recordSet;
    public object RecordSet
    {
        get { return _recordSet; }
        set { _recordSet = value; }
    }

    public string Draw()
    {
        system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());

        object instance;

        instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName);

        //to access de Count of my List
        int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null));

        //i need to do a 
        for(int cont = 0; cont < recordCount; cont++)
        {
            _dataSource[cont].Name; // <-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ???
        }
    }
}
From stackoverflow
  • If you are using reflection (and hence lots of object), why not just cast as an IList (non-generic) instead?

    i.e.

    IList list = (IList)actualList;
    object foo = list[17];
    

    Also - for your original code with Count, you don't mean int.Parse - you should just cast (since we expect Count to be an int).

    Jeff B : Add: if (actualList is IList)
    Marc Gravell : @Jeff B - I disagree; the scenario suggests that we expect it to be a list, hence if the data *isn't* an IList, I'm happy for it to raise an exception. It depends on the scenario, of course; if it was ad-hoc data-binding to either an object, an IList or an IListSource, then "as"/"is" is necessary.
  • Just cast your object to a list first, you don't need reflection here.

  • when i try to create a ILIST object i get a compilation exception:: using generic type 'system.collections.generic.ilist' requires 1 type argument.

    @Marc Gravell it can be a ILIST because i just want to move inside the records

    PD

    Sorry about my english...

    Marc Gravell : As I tried to stress, you want the *non-generic* IList, not IList
    Marc Gravell : i.e. `System.Collections.IList`, not `System.Collections.Generic.IList`
    Marc Gravell : add "using System.Collections;" to the top of the file
  • IList newlist = (IList)_dataSource;

    object x = newlist[1];

    it give to me a compilation exception...

  • Hey hey It works i was missing this part :P System.Collections.IList thanks dude!!

0 comments:

Post a Comment