Hi Mark,

I really can't believe what an idiot I am. What you have described is
exactly what I want, however I was SURE I had tried it like that (i.e
getting the member info from the base class and using it on the instance)
and it hadn't worked.

I just tried it again after reading your post and it works beautifully. I
owe you a beer (or many!).

Many Thanks,

mal

-----Original Message-----
From: Unmoderated discussion of advanced .NET topics.
[mailto:[EMAIL PROTECTED] On Behalf Of Mark Hurd
Sent: Saturday, 27 August 2005 5:41 AM
To: [email protected]
Subject: Re: [ADVANCED-DOTNET] Using Reflection to Obtain Private Members of
Base Classes

On 8/23/05, Malcolm Young <[EMAIL PROTECTED]> wrote:
> Hi Stokes,
>
> Thanks for the reply. I can certainly use the BaseType property to get
> the MemberInfo, but I then want to use that (say) FieldInfo object to set
or
> get the value in the underlying base class. When I try to use it on the
> derived class it throws an exception and (quite rightly) claims that the
> member does not exist. What I really want to do is set that base class
> field on the derived class instance.

When you posted this query I went off and had a play with different
options, like specifying BindingFlags:FlattenHierarchy, but
unsurprisingly found nothing.

However, if you know the /private/ field or property you want to
access, you /must/ know the Type it's from. Just cache the FieldInfo
or PropertyInfo (MemberInfo) from the Type and then the .GetValue and
.SetValue methods only require an untyped Object.

So you ought to be able to cache the MemberInfo object(s) you need to
reference and just apply .GetValue or .SetValue as needed.

If you're dealing with objects that are derived from different base
types, MemberInfo.DeclaringType.IsInstanceOfType will give you a test
on an object to determine if a particular MemberInfo is relevant it.

(MemberInfo is used above mostly as a typing convenience. You have to
treat PropertyInfo and FieldInfo differently when applying .GetValue
and .SetValue because they have different signatures.)

Regards,
Mark Hurd, B.Sc.(Ma.)(Hons.)

===================================
This list is hosted by DevelopMentorR  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to