C # generic type in base class

I am writing a system that has a set of protocol buffers (using protobuf-net), I want to define something like this in an abstract class that they will all inherit:

public byte[] GetBytes()

however, a type argument is required for the protocol serealiser buffer, is there an efficient way to get the type of an inheriting class?

Example:

public byte[] GetBytes()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Serializer.Serialize<T /* what goes here? */>(stream, this);
            return stream.ToArray();
        }
    }
+3
source share
4 answers

Just write "T" correctly?

and then in the class declaration:

public class M<T>

?

- Change

And then when you inherit it:

public class Foo : M<Apple>
+4
source

Define the base class as BaseClass<T>, and then the derived classes, replace T with a serializer type DerivedClass<SerializerType>.

, .

BaseClass<T> where T : SerializerBase

- , .

+3

, protobuf-net .

:

Serializer.NonGeneric.Serialize(stream, this /* Takes an object here */);

, . . ( ).

+3

... protobuf-net . :

[ProtoInclude(typeof(Foo), 20)]
[ProtoInclude(typeof(Bar), 21)]
public abstract class MyBase {
    /* other members */

    public byte[] GetBytes()
    {
        using(MemoryStream ms = new MemoryStream())
        {
            Serializer.Serialize<MyBase>(ms, this); // MyBase can be implicit
            return ms.ToArray();
        }
    }
}
[ProtoContract]
class Foo : MyBase { /* snip */ }
[ProtoContract]
class Bar : MyBase { /* snip */ }

. () ; Serializer.Serialize<Foo>(stream, obj), , , , , , MyBase. () , Deserialize MyBase , Foo Bar .

, :

Serializer.Serialize<BaseType>(dest, obj);
...
BaseType obj = Serializer.Deserialize<BaseType>(source);

Serializer.Serialize<DerivedType>(dest, obj);
...
DerivedType obj = Serializer.Deserialize<DerivedType>(source);

, .

+1

Source: https://habr.com/ru/post/1715292/


All Articles