Common ansestry to Fieldinfo and Propertyinfo

D

damiensawyer

Hi,

I need to invoke .getvalue and .setvalue on fieldinfo and propetyinfo
objects. Even though they're both derived from MemberInfo, they don't
share those two methods. I've finding myself writing the following
types of structure over and over. Is there something I'm missing? Or
some 'funky' 3.5 delegate/lambda expression way of doing this?

Thanks very much in advance,


Damien


MemberInfo MI = this.GetType().GetMember(MemberName)
[0];
object ValueToSet = oDT.Rows[0][col.ColumnName] ??
"";
try
{
//It doesn't seem that Fieldinfo and Propertyinfo
// have a common ancestry, therefore no common map
to .SetValue.
switch (MI.MemberType)
{
case MemberTypes.Field:
((FieldInfo)MI).SetValue(this,
ValueToSet);
break;
case MemberTypes.Property:
((PropertyInfo)MI).SetValue(this,
ValueToSet, null);
break;
default:
break;
}
}
 
J

Jon Skeet [C# MVP]

I need to invoke .getvalue and .setvalue on fieldinfo and propetyinfo
objects. Even though they're both derived from MemberInfo, they don't
share those two methods. I've finding myself writing the following
types of structure over and over. Is there something I'm missing? Or
some 'funky' 3.5 delegate/lambda expression way of doing this?

Bear in mind that they don't have the same parameters either -
FieldInfo.GetValue/SetValue doesn't take a set of arguments as one of
its parameters, whereas PropertyInfo does. In other words, it's hard to
see how they *would* share methods, even if there was some intermediate
common type (or an interface). I guess you could have PropertyInfo with
an overload of GetValue/SetValue which assumed no parameters.

You could always write a pair of utility methods to do this if you find
yourself doing it often though.
 

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