If you have variable types depending on the data you read (like in your case) it doesn't make much sense to use generics. Even if you take @Spontifixus approach you are not able to put all the created elements in one List<T>
, cause due to the different types used in each object you need for each combination your own List<T>
. Also if you later in code like to work with all the arguments, you need to query for each generic type to know how to read the desired value out of the current instance.
If you still think you need generic types (in this case) you can help yourself by using a generic class a creator method and a normal interface:
public interface ICommand
{
int CommandCode { get; set; }
object Argument1 { get; }
object Argument2 { get; }
object Argument3 { get; }
}
public static class Command
{
public static Command<T1, T2, T3> Create<T1, T2, T3>(int code, T1 arg1, T2 arg2, T3 arg3)
{
return new Command<T1, T2, T3>(code, arg1, arg2, arg3);
}
}
public class Command<T1, T2, T3> : ICommand
{
public Command(int code, T1 arg1, T2 arg2, T3 arg3)
{
CommandCode = code;
Argument1 = arg1;
Argument2 = arg2;
Argument3 = arg3;
}
public int CommandCode { get; set; }
public T1 Argument1 { get; set; }
public T2 Argument2 { get; set; }
public T3 Argument3 { get; set; }
object ICommand.Argument1
{
get { return Argument1; }
}
object ICommand.Argument2
{
get { return Argument2; }
}
object ICommand.Argument3
{
get { return Argument3; }
}
}
By using this approach you can create a instance through type inference by calling the creator method and put all of them in one list:
var commands = new List<ICommand>();
var myCommand = Command.Create(3, 4f, true, "hello world");
var commands.Add(myCommand);
Now you got your generic objects in one list, but how do you work with this list? At last you're going all the time using the ICommand
interface and stick to the object
, making the generics useless. But maybe you don't think so and this approach might help.