I am trying to create a c# class dynamically at run time.
using System;
class Hist
{
private int? _min;
private int? _max;
public int? min
{
get{return _min;}
set {_min = value;}
}
public int? max
{
get{return _max;}
set {_max = value;}
}
}
public class ProcessData
{
private string _id;
private string _source;
private int? _currentValue;
private Hist _hist;
public Hist hist
{
get { return _hist; }
set{ _hist = value; }
}
public string id
{
get {return _id;}
set { _id = value; }
}
public string source
{
get {return _source;}
set { _source = value; }
}
public int? currentValue
{
get {return _currentValue;}
set { _currentValue = value; }
}
public int? min
{
get { return (hist != null) ? hist.min : null; }
}
public int? max
{
get { return (hist != null) ? hist.max : null; }
}
}
But i am unable to do this specifically.
return (hist != null) ? hist.max : null;
i just need is the get method for any of the min or max property of ProcessData class.
My code for above task:
var method = parentType.GetMethod("get_" + propertyName);
getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
propertyType, Type.EmptyTypes);
getIl = getPropMthdBldr.GetILGenerator();
var moveTo = getIl.DefineLabel();
getIl.Emit(OpCodes.Ldarg_0);
getIl.EmitCall(OpCodes.Call, parentGetMethod, Type.EmptyTypes);
getIl.Emit(OpCodes.Brtrue_S, moveTo);
getIl.Emit(OpCodes.Ldloca_S, 0);
getIl.Emit(OpCodes.Initobj, typeof(int?));
getIl.Emit(OpCodes.Ldloc_0);
getIl.Emit(OpCodes.Ret);
getIl.MarkLabel(moveTo);
getIl.Emit(OpCodes.Ldarg_0);
getIl.EmitCall(OpCodes.Call, parentGetMethod,Type.EmptyTypes);
getIl.EmitCall(OpCodes.Callvirt, method,Type.EmptyTypes);
getIl.Emit(OpCodes.Ret);
Problem is that you are trying to use local variable that not declared:
You can define required local variable like this:
And your code will be valid, but to improve readability I would advise you to use variable
localinstead index. It could be done like this:P.S. I'll put here code that I've used for generation of classes
HistandProcessData, may be it could be useful for you in some way, in case if my explanation was not sufficient.Main logic in this helper for property creation:
Here is class creation itself:
And finally primitive validation of created classes: