I have problem in generating getterMethod for HasChildren Property in following code.
Could someone help me out of it?
Code in c#
public class Sample
{
public ObservableCollection<Sample> Children { get; set; }
public bool HasChildren { get { return Children?.Count() > 0; } }
}
Code which is not working is quoted here for methodbuilder.
const string propertyName = "HasChildren";
string getterName = $"get_{propertyName}";
MethodInfo countMethodInfo = typeof(System.Linq.Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);
MethodBuilder getHasChildrenMethod = typeBuilder.DefineMethod(getterName, DynamicMethodBuilder.GetMethodAttrs, propertyBuilder.PropertyType, Type.EmptyTypes);
var il = getHasChildrenMethod.GetILGenerator();
var getChildrentMethod = DynamicMethodBuilder.GetGetMethodBuilder(referenceProperty);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, getChildrentMethod); //getter for Children
il.Emit(OpCodes.Ldc_I4_0); //push 0
il.Emit(OpCodes.Callvirt, countMethodInfo); //call count method
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Cgt);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Br_S);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getHasChildrenMethod);
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire