I want to create a generic structure (an array basically) and restrict the possible types to types of ISerializable and a bunch of native data types like int,uint,float,double,char etc. The problem is that I cannot mark these native data types with an interface and my researches stated that it is not possible to use something like an or keyword in generic type constraint construction (where clause). So the question is how can I realize that?
If you are interested in context: I have a BinaryStream class responsible for reading and writing from/to a stream. The custom ISerializable interface has function void Serialize(BinaryStream f)
that either reads or write from/to stream f (depends on state in f). Actually written or read are of course native data types that the structs are made of. These are read or written via f.Transfer(ref data)
. Using a standard BinarySerializer from the .NET framework is not an option, because it has to be done in a custom way.
public class AutoArray<T> : ISerializable where T : ISerializable //or int or uint or float etc.
{
private uint n;
private T[] data;
public void Serialize(BinaryStream f)
{
f.Transfer(ref n);
for (int i = 0; i < n; i++)
if (data[i] is ISerializable) data[i].Serialize(f);
else f.Transfer(ref data[i]);
}
}