开发者

Accessing items in an IList with C# reflection

开发者 https://www.devze.com 2023-01-16 12:24 出处:网络
I have a class with a Items property, which is an IList: class Stuff { IList<OtherStuff> Items; } I want to be able to receive a string wit开发者_如何学JAVAhin a method (I thought of this for

I have a class with a Items property, which is an IList:

class Stuff {
    IList<OtherStuff> Items;
}

I want to be able to receive a string wit开发者_如何学JAVAhin a method (I thought of this format originally: Items[0]) and be able to retrieve the first item of the Items list.

I tried this:

object MyMethod(string s, object obj) {
    return obj.GetType().GetProperty(s).GetValue(obj,null);
}

with s being 'Items[0]' but it doesn't work... Also tried parsing the parameter to access only the property 'Items' of the object and then accessing the index (knowing that it is an IList).

None of these approaches worked... Any thoughts?

Any thoughts?


You can access the property and then can you convert it to a list.

T GetListItem<T>(object obj, string property, int index)
{
    return (obj.GetType().GetProperty(property).GetValue(obj, null) as IList<T>)[index];
}

Working example for your sample code:

OtherStuff item = GetListItem<OtherStuff>(obj, "Items", 0);


If you want to test an object to see if it has a numeric indexer, without regard to whether it is an IList, and then invoke the indexer via reflection, you can try out this method.

It returns true if the object has an indexer, and populates value with the value of the 0th index as well.

public static bool TryGetFirstIndexWithReflection(object o, out object value)
{
    value = null;

    // find an indexer taking only an integer...
    var property = o.GetType().GetProperty("Item", new Type[] { typeof(int) });

    // if the property exists, retrieve the value...
    if (property != null)
    {
        value = property.GetValue(list, new object[] { 0 });
        return true;
    }

    return false;
}

Note that this example makes no attempt to gracefully handle exceptions, such as IndexOutOfRangeException. That's up to you to add if you find it relevant.


Items was not a property, so my approaches wouldn't work. It should be, so I transformed it into a property and now it is working smoothly.


You should try this:

object GetFirstItemByReflection(object obj) {
    return obj.GetType().GetMethod("get_Item").Invoke(obj, new object[] { 0 } );
}

with the appropriate checks.

"get_Item" is the "generated" method used when you access items by index in a collection.

When you get its MethodInfo, you invoke it on your collection, passing it the "0" parameter, to get the first item.

0

精彩评论

暂无评论...
验证码 换一张
取 消