Operating on Multi-type Container Without Knowing the Type
I'm implementing a sort of networked multi-type hash table in C#, and I've
run into a few problems. Each entry has some metadata associated with it,
like a string name and an id number. There are places in my code where I'm
operating on entries, but I don't necessarily need to know the type that
they contain. So, for example, when parsing update packets, I'd like to be
able to do something like this:
entry.Name = ParseName(data);
entry.Id = ParseId(data);
entry = ParseValue(entry, data);
table.Insert(entry);
Where ParseValue() takes the entry, sets some sort of "Value" parameter
and some sort of "Type" parameter based on the data I've gotten from the
network, and returns a generic entry. Then, when I want to do something
with the data, I'd like to be able to do something like switching over
entry.Type and then using the value by casting it to entry.Type. But every
time I've tried to do something like this, I end up needing to put type
parameters in places where I don't know the type. I know that the type is
one of 6 possible types (bool,double,string,List<bool>,List<double>, or
List<string>), but I don't know which of those types it is. Is there a way
I can do this in C#, or even better, is there a way I can change my design
so that this isn't an issue?
Note: All the code above is a simplified representation of what I'm doing
because I didn't want to get into the messy bit twiddling I needed to do
to parse these packets.
Edit: An example of how I might try to use this (I know this isn't valid C#)
foreach( entry in table ) {
switch( entry.Type ) {
case typeof(bool):
displayBool( (bool)(entry.Value) );
break;
case typeof(double):
displayDouble( (double)(entry.Value) );
break;
case typeof(string):
displayString( (string)(entry.Value) );
break;
case typeof(List<bool>):
displayListOfBool( (List<bool>)(entry.Value) );
break;
case typeof(List<double>):
displayListOfDouble( (List<double>)(entry.Value) );
break;
case typeof(List<string>):
displayListOfStrings( (List<string>)(entry.Value) );
break;
}
}
Edit 2: If it helps, the spec for what I'm trying to implement is here:
http://firstforge.wpi.edu/sf/docman/do/downloadDocument/projects.wpilib/docman.root/doc1318
No comments:
Post a Comment