【发布时间】:2017-08-14 07:10:20
【问题描述】:
我有两个接口声明和三个类声明,它们之间的关系是这样的:
interface IProtocolPackage
{
///some declaration
}
public class ProtocolPackage : IProtocolPackage
{
///implementation code for IProtocolPackage
}
interface IProtocolPackage<T> : IProtocolPackage
{
///some declaration
}
public class BytesProtocolPackage : ProtocolPackage, IProtocolPackage<byte[]>
{
///implementation code for IProtocolPackage<byte[]>
}
public class ChargingPileProtocolPackage : BytesProtocolPackage
{
///implementation code for IProtocolPackage<byte[]>
}
然后有一个方法以 IProtocolPackage 类型为参数,如下所示:
public void DecodeCommand(IProtocolPackage<byte> package)
{
///implementation code forDecodeCommand
}
但编译器显示错误说: 无法从“ChargingPileCommandCoder.ChargingPileProtocolPackage”转换为“SHWDTech.Platform.ProtocolCoding.Coding.IProtocolPackage”ChargingPileCommandCoder
我以为我继承了接口 IProtocolPackage 和类 ChargingPileProtocolPackage。 这是怎么发生的?
发生错误的代码:
public IProtocolPackage DecodeProtocol(byte[] bufferBytes, Protocol matchedProtocol)
{
var package = new ChargingPileProtocolPackage { Protocol = matchedProtocol, ReceiveDateTime = DateTime.Now };
var structures = matchedProtocol.ProtocolStructures.ToList();
var currentIndex = 0;
for (var i = 0; i < structures.Count; i++)
{
var structure = structures.First(obj => obj.StructureIndex == i);
var componentDataLength = structure.StructureName == StructureNames.Data && structure.StructureDataLength == 0
? Globals.BytesToInt16(package["DataLength"].ComponentContent, 0, true)
: structure.StructureDataLength;
if (currentIndex + componentDataLength > bufferBytes.Length)
{
package.Status = PackageStatus.NoEnoughBuffer;
return package;
}
if (structure.StructureName == StructureNames.Data)
{
DetectCommand(package, matchedProtocol);
componentDataLength = package.Command.ReceiveBytesLength == 0 ? componentDataLength : package.Command.ReceiveBytesLength;
}
var component = new PackageComponent<byte[]>
{
ComponentName = structure.StructureName,
DataType = structure.DataType,
ComponentIndex = structure.StructureIndex,
ComponentContent = bufferBytes.SubBytes(currentIndex, currentIndex + componentDataLength)
};
currentIndex += componentDataLength;
package[structure.StructureName] = component;
}
DecodeCommand(package);
return package;
}
public IProtocolPackage EncodeCommand(IProtocolCommand command, Dictionary<string, byte[]> paramBytes = null)
{
throw new NotImplementedException();
}
public void DoDelive(IProtocolPackage package, IPackageSource source)
{
throw new NotImplementedException();
}
public IDataConverter<byte> DataConverter { get; set; }
public void DecodeCommand(IProtocolPackage<byte> package)
{
throw new NotImplementedException();
}
public void DetectCommand(IProtocolPackage<byte> package, IProtocol matchedProtocol)
{
throw new NotImplementedException();
}
}
【问题讨论】:
-
检查命名空间是否相同,可能你在两个命名空间中有重复的接口定义?
-
发布您遇到实际错误的代码。您发布的代码似乎没有任何错误。
-
此错误在哪里发生?我看不到任何将一个类实例转换为另一个类实例的代码。