Command<CommandResult>
을 인수로 사용하는 ExecCommand
메서드가 있습니다. 그러나 내가 CommandResult
유도 된 제네릭 형식으로 명령을 전달하려고 할 때 빌드 실패제네릭 형식을 캐스팅 할 때 오류가 발생했습니다.
class Program
{
class CommandResult
{
}
class Command<TResult> where TResult : CommandResult, new()
{
internal virtual TResult ParseReply(object reply)
{
return new TResult();
}
public Action<TResult> CommandCompleteCallback = null;
}
class CommandA : Command<CommandResult>
{
}
class CommandResultForB : CommandResult
{
}
class CommandB : Command<CommandResultForB>
{
internal override CommandResultForB ParseReply(object reply)
{
return new CommandResultForB();
}
}
static Queue<Command<CommandResult>> commandQueue = new Queue<Command<CommandResult>>();
static void ThreadLoop()
{
// This threadloop transmits the first command on the queue to external library when executeNextCommand is set (it's using Peek, so the command stays in the queue until the external library calls OnCommandCompleteResponse()
}
static void OnCommandCompleteRespose(object reply)
{
// called from external library when command is complete
lock (commandQueue)
{
var command = commandQueue.Dequeue();
if (command.CommandCompleteCallback != null)
command.CommandCompleteCallback(command.ParseReply(reply));
}
}
static void ExecCommand(Command<CommandResult> command)
{
lock (commandQueue)
{
commandQueue.Enqueue(command);
if (commandQueue.Count == 1)
executeNextCommand.Set();
}
}
static void Main(string[] args)
{
ExecCommand(new CommandA());
ExecCommand(new CommandB()); // <-- this is the offending line
}
}
어떤 아이디어를 내가 'CommandB에서 명령으로 변환 할 수 없습니다'오류를 얻을 이유는 무엇입니까? CommandResultForB
을 기본 클래스 CommandResult
에 자동으로 캐스팅 할 수없는 이유는 무엇입니까? 당신이 CommandB
유형의 인스턴스로 ExecuteCommand()
를 호출하고 여전히 가능한 한 일반적인 싶은 경우
제네릭이 아닌 C++ 템플릿이기 때문에. – helb