views:

1110

answers:

5

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!! ???
        }
    }
}
+3  A: 

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).

Marc Gravell
Add: if (actualList is IList)
Jeff B
@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.
Marc Gravell
A: 

Just cast your object to a list first, you don't need reflection here.

FlySwat
A: 

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...

As I tried to stress, you want the *non-generic* IList, not IList<T>
Marc Gravell
i.e. `System.Collections.IList`, not `System.Collections.Generic.IList<T>`
Marc Gravell
yes, but the code you post give me a compilation exception.i have now the List in a Object, but inside the class i want to cast the object to a List a with a For access all the Items that the List Has
add "using System.Collections;" to the top of the file
Marc Gravell
A: 

IList newlist = (IList)_dataSource;

object x = newlist[1];

it give to me a compilation exception...

A: 

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