[英]Generic interface implementation - order of execution
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);
两种实现都使用MemoryStream Serialize(T obj);
My question is why does the list version use the MemoryStream Serialize(T obj);
我的问题是为什么列表版本使用MemoryStream Serialize(T obj);
and not the Serialize(IList<T> list);
而不是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). 因此,当将IList<BarcodeScannerModel>
传递给Serialize()
它会正确地选择obj
重载(请注意,正确地不等于所需的)。
If you want it to call 如果你想要它打电话
MemoryStream Serialize(IList<T> list);
then you need to define your serializer
like: 然后你需要定义你的serializer
如:
ISerializer<BarcodeScannerModel> serializer = new Serializer<BarcodeScannerModel>();
Basically you are doubling up on IList
s 基本上你是在加倍IList
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. 我的猜测是因为您的接口方法是为List<T>
定义的,同时您将List<Barcode...>
作为T
传递,您的实际参数不是预期的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.