使用策略模式处理不同的消息类型

问题描述 投票:0回答:1

我有一个包含多种不同消息类型的日志文件。每种消息类型通过标签35进行区分。例如,标签35可以等于“ i”,“ s”,“ g”,“ p”等。每种标签对应于不同类型的消息。例如,标记35 ='i'对应于QuoteMessage,而标记35 ='g'对应于NewOrderMessage。

我想拥有一个叫做的功能

public class MessageProcessor
{

private readonly IEnumerable<ICommand> _commands;

public List<IMessage> ProcessMessageByType(MessageType type);
    var command = _commands.Where(c => (char)type == c.Type).First();
    return command.Do(); // Returns a list of messages of this type.
}
public interface ICommand
{
   string RegexMatch { get; set; }
   bool IsMatch(string input);
   List<IMessage> Do();
}

public class ProcessTagICommand : ICommand
{
   public string RegexMatch = "i";
   bool IsMatch(string input) => Regex.Match(input, RegexMatch).Success;
   List<IMessage> Do()
   {
      return // a list of quoteMessages. This won't compile :'(
   }
}

我遇到的问题是,对于每条消息,我需要返回不同类型的IMessage,即使它们实现了IMessage的接口,也不会隐式转换为IMessage类型。例如,QuoteMessage可能是:

public interface IMessage
{
    DateTime Timestamp { get; set; }
}

public class QuoteMessage : IMessage
{

}

public class OrderMessage : IMessage
{

}

从上面的command.Do(),我将返回一个List<QuoteMessage>,由于某种原因,即使它实现了其接口,也无法将其转换为IMessage

有人可以向我解释实现我要达到的目标的最佳方法吗?

c# interface strategy-pattern
1个回答
0
投票
最简单的响应是使用IEnumerable

public interface ICommand { IEnumerable<IMessage> Do(); } public class ProcessTagICommand : ICommand { public IEnumerable<IMessage> Do() { return new List<QuoteMessage>(); } }

这是因为IEnumerable允许将协变类型设置为IMessage,您可以在dotnet中了解有关协变和逆变的更多信息:Covariance and Contravariance
© www.soinside.com 2019 - 2024. All rights reserved.