2

I am using widely using foovar.GetType().GetProperty("PropertyName").GetValue(foovar) to get the property value of a variable variable through reflection. But it doesn't appears to work on interface types.

IFoo foo = GetFoo();
string fooName= foo.Name; //It works perfectly

I am working with a third party assembly so I don't have access to the implementation. There is a 'Name' property, and I can get the value. But can't through reflection.

When I try string s = (string)foo.GetType().GetProperty("Name").GetValue(foo); i get a null error: there is no 'Name' property

I have checked PropertyInfo[] pi = foo.GetType().GetProperties(); and I can see about 200 properties, none of these is "Name". In fact many other 'intellisense properties' doesen't show up.

¿How can I retrive the value of a property of an interface type?

Thanks!

4

1 回答 1

3

The returned object may implement IFoo explicitly, so the Name property will be private. You can use the interface type instead:

object property = typeof(IFoo).GetProperty("Name").GetValue(foo);

EDIT: If that doesn't work, then I can only assume the property is actually defined on some other interface which IFoo implements e.g.

public interface IBase
{
    string Name { get; }
}

public interface IFoo : IBase
{
}

In this case you'll need to find the actual interface which declares Name and use that.

于 2013-08-24T13:47:58.200 回答