Access base class fields using reflection

J

J E E

Hi!

Is it possible to access fields in a derived class using reflection?

Code below works fine when I access it as a private member in the Page
class, but not when accessing base class member through an interface
reference.

I have tried to change the snd argement to SetAttribute method from
'Name', 'set_Name' to '_name'. That doesn't seem to be the problem. I
have also tried using different binding flags, without luck.

Any ideas on what I am doing wrong?

public interface IAttributeMain
{
string ID { get; set; }
string Name { get; set; }
string Type { get; set; }
}

public class AttributeMain : IAttributeMain
{
private string _id;
private string _name;
private string _type;

// Set/Get Implementation
...

}

public class Page : AttributeMain
{
}

private void SetAttribute(IAttributeMain attr, string Name, string
Value)
{
if (attr!= null)
{
Type type = attr.GetType();
fieldInfo = type.GetField(Name, BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Public);
if (fieldInfo != null)
{
fieldInfo.SetValue(attr, Value);
}
}
}
}

static Main()
{
IAttributeMain attr = new Page();
SetAttribute(attr, "Name", "10");
}

/J E E
 
N

Nicholas Paldino [.NET/C# MVP]

J E E,

Interfaces don't have fields, so that is why this is failing. What you
have to do is get the implementation of the interface, and then you can
perform what you are doing.

However, this is a very, very bad design. If you want to get at the
fields, then you should expose them in some manner that fits into the
overall design of your application. Depending on reflection to perform
operations on fields/methods/properties that are hidden because of
accessiblity is a bad, bad idea. There is a reason these things are marked
private/internal/protected.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top