I have the following generic interface
public interface ISerializer<T>
{
MemoryStream Serialize(IList<T> list);
MemoryStream Serialize(T obj);
}
When I implement the interface as follows
ISerializer<IList<BarcodeScannerModel>> Serializer = new Serializer<IList<BarcodeScannerModel>>();
var memstream = Serializer.Serialize(list);
object myObject = new object();
ISerializer<object> Serializer = new Serializer<object>();
var memStr = Serializer .Serialize(myObject);
Both implementations use MemoryStream Serialize(T obj);
My question is why does the list version use the MemoryStream Serialize(T obj);
and not the Serialize(IList<T> list);
version?
The reason that your call to
var memstream = Serializer.Serialize(list);
is calling
MemoryStream Serialize(T obj);
is that when the generics are "filled out" your interface "looks like" (pseudocode):
public interface ISerializer<IList<BarcodeScannerModel>>
{
MemoryStream Serialize(IList<IList<BarcodeScannerModel>> list);
MemoryStream Serialize(IList<BarcodeScannerModel> obj);
}
and so when passing an IList<BarcodeScannerModel>
to Serialize()
it correctly chooses the obj
overload (note that correctly does not equate to desired).
If you want it to call
MemoryStream Serialize(IList<T> list);
then you need to define your serializer
like:
ISerializer<BarcodeScannerModel> serializer = new Serializer<BarcodeScannerModel>();
Basically you are doubling up on IList
s
Have you tried
ISerializer<BarcodeScannerModel> Serializer = new ...
My guess is that because your interface method is defined for List<T>
and in the same time you pass List<Barcode...>
as T
, your actual parameter is not of the expected type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.