I have a class with two properties ( Name
and Value
). The property Name
is a string
, already the property Value
want to leave the type variable.
public class Field<TValue>
{
public string Name { get; set; }
public TValue Value { get; set; }
public Field()
{
}
public Field(string name, TValue value)
{
this.Name = name;
this.Value = value;
}
}
In this case it would be simple to instantiate this class with the desired type:
var field1 = new Field<int>("Nome1", 1);
var field2 = new Field<string>("Nome2", "Valor2");
The problem is that I have an intermediate class that uses the class Field
as property:
public class MyClass
{
public string Prop1 { get; set; }
public int Prop2 { get; set; }
public Field<TValue>[] FieldArray { get; set; }
}
That is, I want to be able to have a generic% s of Field's , but this last example is not valid for the compiler.
My final goal is something like this:
var myClassObject = new MyClass();
myClassObject.Prop1 = "Teste";
myClassObject.Prop2 = 10;
myClassObject.FieldArray = new Field<TValue>[10];
myClassObject.FieldArray[0] = new Field<string>();
myClassObject.FieldArray[0].Name = "Field1";
myClassObject.FieldArray[0].Value = "Value1";
myClassObject.FieldArray[1] = new Field<int>();
myClassObject.FieldArray[1].Name = "Field2";
myClassObject.FieldArray[1].Value = 2;
Does language allow you to do something like this? What would be the correct way?