Re: Generics Questions

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Marc Gravell wrote:
For info, one other approach is to pass in (or register centrally) an
interface-implementation per type - i.e. you might have an;

interface IByteConverter<T> {
T ReadFromBuffer(byte[] buffer, int offset);
int WriteToBuffer(T value, byte[] buffer. int offset);
}

You then might have 4 concrete implementations of this, each doing
their own thing. You can either pass the implementation into the
method as a parameter, or you could register them against a generic
cache class:

static ByteConverter<T> {
public T Default {get;set;}
}

and have a bit of code assign:

ByteConverter<int> = new Int32ByteConverter();
ByteConverter<string> = new StringByteConverter();

This is really good if you want to leave it open for extension by the user.

If you don't care, then... nevermind, you can't inherit a public class from
an internal abstract class due to restrictions in .NET.


I use a similar approach in my "protobuf-net" implementation:
http://code.google.com/p/protobuf-net/source/browse#svn/trunk/protobuf-net/Serializers

(look at ISerializer and SerializerCache, etc; the rest are
differerent implementations)

Marc


.



Relevant Pages