Joerg Battermann wrote:
Argh - ok that's bad (for me). Basically I have an oodbms attached to
some of my classes.. and adding indexes relies in knowing the field
names. Bad... but oh well.
Hmm... well... the following code will give you the field for
automatically generated properties on all but the most crazy compilers,
where it could potentially do odd things (for example, if the automatic
property's getter strangly called a method before accessing the field
and that method happened to contain 0x7B in its token).
Cecil would be useful here and could parse the IL instead of guessing
that the first instance of 0x7B is the ldfld instruction so the token
will come next.
Having said that, it does work for any reasonable compiler and I wanted
to keep the code simple:
private static FieldInfo GetBackingField (PropertyInfo property)
{
if (!(property.Can Read && property.CanWri te))
{
throw new NotSupportedExc eption("Not an automatic property");
}
byte[] getter =
property.GetGet Method().GetMet hodBody().GetIL AsByteArray();
byte ldfld = (byte)(property .GetGetMethod() .IsStatic ?
OpCodes.Ldsfld : OpCodes.Ldfld). Value;
byte[] fieldToken = getter.SkipWhil e(b =b !=
ldfld).Skip(1). Take(4).ToArray ();
if (fieldToken.Len gth != 4)
{
throw new NotSupportedExc eption("Not an automatic property");
}
FieldInfo field =
property.Declar ingType.Module. ResolveField(Bi tConverter.ToIn t32(fieldToken,
0));
if (field == null)
{
throw new NotSupportedExc eption("Not an automatic property");
}
//Not sure about this: compilers don't strictly have to add this
attribute.
if (!field.IsDefin ed(typeof(Compi lerGeneratedAtt ribute), false))
{
throw new NotSupportedExc eption("Not an automatic property");
}
return field;
}
Alun Harford