gpt4 book ai didi

c# - 如何使用逆变参数将泛型接口(interface)转换为基类型?

转载 作者:行者123 更新时间:2023-11-30 12:33:25 25 4
gpt4 key购买 nike

我正在尝试开发通用命令处理器。我想创建实现给定接口(interface)的命令处理程序类。我将使用控制反转根据收到的命令类型动态地创建适当类的实例。然后我想以通用方式调用类的“Execute”方法。

我可以使用协变类型参数来完成这项工作,但在这种情况下,我不能将泛型类型参数用作方法参数。

看起来逆变方法应该可行,因为它允许我根据需要声明方法参数,但不幸的是,类的实例无法转换为基接口(interface)。

下面的代码说明了这个问题:

using System;
using System.Diagnostics;

namespace ConsoleApplication2
{
// Command classes

public class CommandMessage
{
public DateTime IssuedAt { get; set; }
}

public class CreateOrderMessage : CommandMessage
{
public string CustomerName { get; set; }
}

// Covariant solution

public interface ICommandMessageHandler1<out T> where T : CommandMessage
{
void Execute(CommandMessage command);
}

public class CreateOrderHandler1 : ICommandMessageHandler1<CreateOrderMessage>
{
public void Execute(CommandMessage command)
{
// An explicit typecast is required
var createOrderMessage = (CreateOrderMessage) command;
Debug.WriteLine("CustomerName: " + createOrderMessage.CustomerName);
}
}

// Contravariant attempt (doesn't work)

public interface ICommandMessageHandler2<in T> where T : CommandMessage
{
void Execute(T command);
}

public class CreateOrderHandler2 : ICommandMessageHandler2<CreateOrderMessage>
{
public void Execute(CreateOrderMessage command)
{
// Ideally, no typecast would be required
Debug.WriteLine("CustomerName: " + command.CustomerName);
}
}

class Program
{
static void Main(string[] args)
{
var message = new CreateOrderMessage {CustomerName = "ACME"};

// This code works
var handler1 = new CreateOrderHandler1();
ICommandMessageHandler1<CreateOrderMessage> handler1b = handler1;
var handler1c = (ICommandMessageHandler1<CommandMessage>) handler1;
handler1c.Execute(message);

// This code throws InvalidCastException
var handler2 = new CreateOrderHandler2();
ICommandMessageHandler2<CreateOrderMessage> handler2b = handler2;
var handler2c = (ICommandMessageHandler2<CommandMessage>)handler2; // throws InvalidCastException
handler2c.Execute(message);
}
}
}

最佳答案

您可以使用 out 转换通用接口(interface)通用参数仅用于具有更特定 参数的接口(interface)。例如。 ICommandMessageHandler1<CommandMessage>可以转换为 ICommandMessageHandler2<CreateOrderMessage> ( Execute(CommandMessage command) 也将接受 CreateOrderMessage ),但反之则不然。

试着想一想,例如,如果 Actor 抛出一个 InvalidCastException在您的代码中将被允许,如果您调用 handler2c.Execute(new CommandMessage()) 会发生什么?

关于c# - 如何使用逆变参数将泛型接口(interface)转换为基类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9298340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com