C#泛型基础知识?

时间:2013-12-06 05:53:00

标签: c# generics

我有以下两个课程

public class CommandFetcher : ICommandFetcher
{
  private readonly Dictionary<TypeAndVersion, Type> _configuration;

  public CommandFetcher(Dictionary<TypeAndVersion, Type> configuration)
  {
      _configuration = configuration;
  }

    public ICommand FetchFrom(MessageEnvelope messageEnvelope)
    {
        TypeAndVersion typeAndVersion = new TypeAndVersion(messageEnvelope.MetaData.MessageType,
            messageEnvelope.MetaData.MessageTypeVersion);
        return (ICommand)JsonConvert.DeserializeObject(messageEnvelope.MessageData, _configuration[typeAndVersion]);
    }
}

public class MessageDeserializer : IMessageDeserializer
{
    private readonly IDictionary<TypeAndVersion, Type> _configuration;

    public MessageDeserializer(IDictionary<TypeAndVersion, Type> configuration)
    {
        _configuration = configuration;
    }

    public IMessage Deserialize(string messageData, IMetaData metaData)
    {
        var typeAndVersion = new TypeAndVersion(metaData.MessageType, metaData.MessageTypeVersion);
        if (!_configuration.ContainsKey(typeAndVersion))
            throw new InvalidOperationException("Invalid version");
        return (IMessage) JsonConvert.DeserializeObject(messageData, _configuration[typeAndVersion]);
    }
}

我在两个类中都重写了配置部分 但现在我希望将MessageDeserializer类的配置转换为CommandFetcher类 我该怎么做 ? 谢谢!

3 个答案:

答案 0 :(得分:1)

不知道我是否正确地阅读了你的问题...但听起来你想要在MessageDesrializer中实例化一个CommandFetcher?如果这是正确的,你可以尝试在CommandFetcher上使用字典而不是字典

答案 1 :(得分:1)

您的问题有多个问题:

  1. 您没有说任何关于类之间的依赖关系。是否有人使用另一个?
  2. 您没有分享configuration实际上是什么。每个班级都需要自己的配置吗?
  3. 所以这是我的猜测:你的两个班级实际上使用相同的_configuration。在这种情况下,这与泛型无关。您需要做的就是将相同的Dictionary传递给两个对象构造函数。

答案 2 :(得分:1)

如果您尝试创建一个处理这两种情况的通用方法,它将看起来像这样:

public class GenericDeserializer<T> : IGenericDeserializer
{
    private readonly IDictionary<TypeAndVersion, Type> _configuration;

    public GenericDeserializer(IDictionary<TypeAndVersion, Type> configuration)
    {
        _configuration = configuration;
    }

    public T Deserialize(string messageData, IMetaData metaData)
    {
        var typeAndVersion = new TypeAndVersion(metaData.MessageType, metaData.MessageTypeVersion);
        if (!_configuration.ContainsKey(typeAndVersion))
            throw new InvalidOperationException("Invalid version");
        return (T)JsonConvert.DeserializeObject(messageData, _configuration[typeAndVersion]);
    }
}

也就是说,您需要规范化ICommand和IMessage,并为ICommandFetcher和IMessageDeserializer创建一个通用接口。