开发者

Why do you need to specify generic type for the following code

I have an interface

public interface ITcpSerializable<T>
{
    Byte[] Serialize();
    T Deserialize(Byte[] data);
}

In a seperate class of mine I wish to expose a following property.

public List<ITcpSerializable> RegisteredTypes { get; set; }

The problem is I am getting th开发者_JAVA技巧e following error.

Using the generic type 'ITcpSerializable' requires 1 type arguments

Now I understand the error and how I could correct it but the problem is I do not wish to restrict my RegisteredTypes property to a specific typed implementation of my ITcpSerializable interface.

Is there a way around this problem? Hopefully what I am trying to accomplish is clear.

EDIT: OK i have completely stuffed up what I was trying to explain. Just clicked that my thinking was completely skewed. Please see this question for what I was actually asking: Constrain public property to specific types in List<Type>


You have to make a ITcpSerializable form of ITcpSerializable<T>. Then inherit from that with your generic version.

interface ITcpSerializable { }
interface ITcpSerializable<T> : ITcpSerializable { }


You can create a non-generic ITcpSerializable and inherit ITcpSerializable<T> from the new non-generic interface.


The Generic type argument definition in the interface is designed to require type safe results of a specific type when deserializing an object of a given type.

The particular use-case doesn't make sense to me, because you'd need to have an instance of an object in order to deserialize a different instance - which is not usually the way you'd want to go.

I understand you want to require that there's a strongly typed deserializer, but it would make sense to use some other pattern (like a Factory)

Furthermore, your input data is a byte[] - unless there is some other metadata, you have no way of knowing which implementor of ITCPSerializable needs to be called in order to get the correct concrete type.

The type information may be contained in the data (i.e. some header that includes type information) or by some other contract (i.e. always the same type).

The serialize method DOES make sense - because it's reasonable to ask an object for a serialized instance of itself, but the other way around is usually done by some other means.

So the solution to your problem would be to remove the generic type definition (which doesn't help you) and the Deserialize method (which doesn't make sense in this context), and just keep the Serialize method.

as in:

 public interface ITcpSerializable
{
    Byte[] Serialize();
}

And implement the Deserialize by using a factory.


You probably want to make your separate class generic also then, like:

public class MyClass<T> {
    public List<ITcpSerializable<T>> RegisteredTypes { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜