Please see the complete code below. My solution works like:
var myForm = new Form();
var int_value = myForm.Fields
.OfType<IntegerFormField>()
.First(c => c.Name == "c1").GetValue();
var decimal_value = myForm.Fields
.OfType<DecimalFormField>()
.First(c => c.Name == "c2").GetValue();
The field interfaces:
public interface IFormField
{
object GetValue();
string Name { get; }
}
public interface IFormField<T> : IFormField
{
T GetValue();
}
The abstract base class for all form fields:
abstract class FormFieldBase<T> : IFormField<T>
{
private readonly T _value;
public FormFieldBase(T value, string name)
{
_value = value;
Name = name;
}
#region IFormField<T> Members
public virtual T GetValue()
{
return _value;
}
#endregion
#region IFormField Members
object IFormField.GetValue()
{
return _value;
}
public string Name { get; private set; }
#endregion
}
Two sample form field implementation:
class IntegerFormField : FormFieldBase<int>
{
public IntegerFormField(int value, string name) : base(value, name) { }
}
class DecimalFormField : FormFieldBase<decimal>
{
public DecimalFormField(Decimal value, string name) : base(value, name) { }
}
The Form Class:
class Form
{
public IList<IFormField> Fields
{
get
{
return new List<IFormField>(){
new IntegerFormField(10, "c1"),
new DecimalFormField(200, "c2")
};
}
}
}
HTH