I’m working on building a dynamic calculation framework, that will build a generic GUI based on the calculation types and attributes on those types.
For instance, I might have a simple Adder calculator (forgive the simplicity, but when putting together frameworks, I like to start simple and work my way up), that looks like this:
[CalculatorAttribute("This calculator add X+Y=Z")]
class AdderCalculator : CalculatorBase
{
[CalculationValueAttribute(InputOutputEnum.InputValue, "First Input")]
public int? X
{
set { m_X = value; m_Z = null;}
get { return m_X; }
}
[CalculationValueAttribute(InputOutputEnum.InputValue, "Second Input")]
public int? Y
{
set{ m_Y = value; m_Z = null;}
get { return m_Y; }
}
[CalculationValueAttribute(InputOutputEnum.OutputValue, "Output")]
public int? Z
{
get { return m_Z; }
}
public AdderCalculator()
{
m_X = m_Y = m_Z = null;
}
public override Boolean ReadyToCalc()
{
return (m_X != null && m_Y != null);
}
public override Boolean NeedToCalc()
{
return (m_Z == null);
}
public override void Calculate()
{
if(ReadyToCalc()){ m_Z = m_X + m_Y;}
}
private int? m_X, m_Y, m_Z;
}
(forgive the whitespace, I tried to reduce the size as much as possible without sacrificing too much readability).
I’m using the nullable type to allow me to distinguish unset values from set values
Now, in my GUI, I’m using TextBoxes to collect the input information. From TextBox, I can only get the Text (String). Using reflection, I know the name of the property and can get it’s setter (set_X or set_Y in this case).
The type of the field is (of course) int? (nullable int), but I can use:
PropertyInfo.PropertyType.GetGenericArguments();
method to get the Int32 type (or Int64, whichever may be the case).
So, given that I can end up with a instance of a Type object, can anyone recommend a generic way to convert String to that type
What I have considered is:
- Implement a string setter method in my AdderCalculator:
set_X(String s) - Change my control type to
NumericUpDown, as it will return aDecimal - change the type to
Decimal, butDecimalcan’t directly convert fromStringeither (it can use parse, but that is tougher from a generic standpoint
Can anyone provide additional insight?
Just to get the answer out where it can be clearly seen, the code I ended up with is:
I still need to add some exception protection for invalid values, but this works with the property type being any numeric type (byte, short, int, int32, int64, float, double, Decimal, etc…)