This is the first class:
public class TextBoxInt : TextBox
{
public int min;
public int max;
public Value<int> value;
public virtual void Update(object sender, EventArgs e)
{
int newValue;
if (int.TryParse(Text, out newValue))
{
if (newValue < min || newValue > max)
{
//do thing A
}
value.Set(newValue);
Text = value.Get().ToString();
}
else
{
Text = value.Get().ToString();
Focus();
}
}
public TextBoxInt(Value<int> value, int min, int max)
{
this.value = value;
this.min = min;
this.max = max;
Text = value.Get().ToString();
LostFocus += new EventHandler(update);
}
}
This is the second class:
public class TextBoxFloat : TextBox
{
public float min;
public float max;
public Value<float> value;
public virtual void Update(object sender, EventArgs e)
{
float newValue;
if (float.TryParse(Text, out newValue))
{
if (newValue < min || newValue > max)
{
//do thing A
}
value.Set(newValue);
Text = value.Get().ToString();
}
else
{
Text = value.Get().ToString();
Focus();
}
}
public TextBoxFloat(Value<float> value, float min, float max)
{
this.value = value;
this.min = min;
this.max = max;
Text = value.Get().ToString();
LostFocus += new EventHandler(update);
}
}
Also, this is the Value class :
public class Value<T>
{
private T value;
private List<IValueListener<T>> listeners = new List<IValueListener<T>>();
public Value(T value)
{
this.value = value;
}
public T Get()
{
return value;
}
public void Set(T value)
{
this.value = value;
foreach (IValueListener<T> listener in listeners)
{
listener.ValueUpdated(this);
}
}
public void AddListener(IValueListener<T> listener)
{
listeners.Add(listener);
}
public void RemoveListener(IValueListener<T> listener)
{
listeners.Remove(listener);
}
}
As you can see, the first two classes are basically the same class. The only difference is the type. First one is int
, the other one float
. It seems that I would make for nicer code if I could combine those two into a single class.
I can set min
and max
to be floats and just cast them to int
when needed if it's an int class. I'd just make sure I pass "whole" floats when the type is int.
Is there any way I can do it without duplicating Update()
method (If int do codeForInt, else if float do sameCodeButForFloat
)?
Also, even if I do duplicate the code, I run into a problem with value.Set(newValue);
- in one case newValue
would be int
, in other it would be float
, and I can't cast either to T
.
Also, is there a way to limit the generic type? To specify it can only be int or a float?
Should I just leave them as two classes, or is there a way to unify them?