I'm not sure why it does not work as what I expect. I'm trying to define a dynamic private property (just for experiment) but somehow it's always found by Reflection like as it's public (no BindingFlags.NonPublic
is required to find it). Here is the Emit code:
var prop = typeBuilder.DefineProperty("MyProperty", PropertyAttributes.HasDefault,
typeof(string), null);
var backingField = typeBuilder.DefineField("_myProperty", typeof(string), FieldAttributes.Private);
var getter = typeBuilder.DefineMethod("get_MyProperty", MethodAttributes.Private, typeof(string), null);
var getterIL = getter.GetILGenerator();
getterIL.Emit(OpCodes.Ldarg_0);
getterIL.Emit(OpCodes.Ldfld, backingField);
getterIL.Emit(OpCodes.Ret);
var setter = typeBuilder.DefineMethod("set_MyProperty", MethodAttributes.Private, null, new []{typeof(string)});
var setterIL = setter.GetILGenerator();
setterIL.Emit(OpCodes.Ldarg_0);
setterIL.Emit(OpCodes.Ldarg_1);
setterIL.Emit(OpCodes.Stfld, backingField);
setterIL.Emit(OpCodes.Ret);
prop.SetGetMethod(getter);
prop.SetSetMethod(setter);
var t = typeBuilder.CreateType();
Now I expect the Reflection won't be able to find it without using the BindingFlags.NonPublic
but it's still be found with this code:
var myProp = t.GetProperty("MyProperty");//this should not be able to
//find the property, but it does.
In fact it's actually generated as public because if I try finding it as private, the result will be null:
//this will be null
var myProp = t.GetProperty("MyProperty", BindingFlags.Instance | BindingFlags.NonPublic);
So looks like it's very mysterious about how to define private property using Emit. I've even searched for that exact keywords but there are just a new result related (in title) but not actually involving the problem.
I hope you could give me some solution for this problem. Thank you.
Aucun commentaire:
Enregistrer un commentaire