How to access a property for each memebr of an indexer using reflection in C# .net 2.0
I have the following method:
object GetIndexer()
The result of the method is an indexer of the type:
SomeCollection<T>
Now T can be anything, by I know that each T extends the type Y.
I tried casting
SomeCollection<Y> result= (SomeCollection<Y>) GetIndexer()
It didn't work.
What I need to know is how to access a proper开发者_运维问答ty for each item in the indexer SomeCollection using Reflection?
Use GetType()
for each item, then call either GetProperties() or GetProperty(propertyName) to obtain the PropertyInfo. With this, you then call GetValue()
passing in your object.
An example:
List<object> objects = new List<object>();
// Fill the list
foreach (object obj in objects)
{
Type t = obj.GetType();
PropertyInfo property = t.GetProperty("Foo");
property.SetValue(obj, "FooFoo", null);
Console.WriteLine(property.GetValue(obj, null));
}
Some context would be helpful, but it sounds like you've got something like
class Foo<T> where T : Y {
object GetIndexer() { /* ... */ }
}
In that case, why not just
SomeCollection<Y> GetIndexer() { /* */ }
That way, no cast is required.
But I am a little confused by your use of the term 'indexer'. An indexer for a C# is a way of overloading the [] operator for a type, so that you can do things like:
MyCollectionType c = new MyCollectionType()
c["someValue"]
They are defined like so:
class MyCollectionType {
public string this [string index] // This particular indexer maps strings to strings, but we could use other types if we wished.
get {} // Defines what to do when people do myCollection["foo"]
set {} // Defines what to do when people do myCollection["foo"] = "bar"
}
An object of type SomeCollection<Y>
isn't an indexer, it's a collection.
Is SomeCollection<T>
enumerable? If so you could do
var transformed = new SomeCollection<Y>();
var someObjectCollection = (IEnumberable)GetIndexer();
foreach (var someObjectin someObjectCollection);
transformed.Add((Y)someObject);
Or wait until C# 4.0 gives us more covariance and contravariance options.
To loop through a list is the process of enumeration. It is easiest with an Enumerator. That is (in C#): anything that implements IEnumberable
.
If the object you are trying to loop through is one of your own making, I recommend implementing IEnumberable. If it isn't, can you give more info about this specific 3rd party object? Maybe there are others who've also needed to use it in this way and maybe their work can be found by one of us online.
精彩评论