Emit private field get/set (FieldAccessException) [modified]
-
I'm working on a serializer and I've run into an issue with private field access. When I emit and run the IL code to access the private field of a class, it results in a FieldAccessException. I've gone looking for information on this but found very little. One of the suggestions was that the class I emit, that has the code that accesses the private fields must be have a special permissions attribute. So I added the following to my type builder for the class:
Type[] ctorParams = new Type[] { typeof(SecurityAction) }; ConstructorInfo ci = typeof(ReflectionPermissionAttribute).GetConstructor(ctorParams); PropertyInfo pi = typeof(ReflectionPermissionAttribute).GetProperty("Unrestricted"); CustomAttributeBuilder cab = new CustomAttributeBuilder(ci, new object[] { SecurityAction.Assert }, new PropertyInfo[] { pi }, new object[] { true }); typeBuilder.SetCustomAttribute(cab);
However, this still results in the same FieldAccessException. Does anyone have any experience with private field access via the ILGenerator, and could shed some light on this for me, I would be very happy. I've also tried:typeBuilder.AddDeclarativeSecurity(SecurityAction.Demand, new PermissionSet(PermissionState.Unrestricted));
With the same result.