【问题标题】:Generics, Polymorphism and Inheritence泛型、多态性和继承
【发布时间】:2014-06-01 11:24:09
【问题描述】:

我目前正在尝试实现一个抽象算法

后者通过开发者提供的解析器将Data转换成Xml 进入Expected指定类型

这种转换器的接口:

public interface IParser<TExcpected, TSource> where TExcpected : class where TSource : class
{
    TExcpected Parse(TSource source);
}

这一切都适用于许多不同的类型,直到需要稍微专门化它 并通过指定的算法将键值对转换为元数据 原型:

public abstract class KeyValuePairParserBase<TKey, TValue, TMetadata> 
    : IParser<TMetadata, IEnumerable<KeyValuePair<TKey, TValue>>> where TMetadata : class
{
    public abstract TMetadata Parse(IEnumerable<KeyValuePair<TKey, TValue>> source);
}

然后我实现了一个默认类来代替开发者的类

 class KeyValuePairParser<TKey,TValue>
    : KeyValuePairParserBase<TKey, TValue,KeyValuePairList<TKey,TValue>>
{
   public override KeyValuePairList<TKey,TValue> Parse(IEnumerable<KeyValuePair<TKey, TValue>> source)
    {.....}
}

其中 KeyValuePairList 是一个通用的 Xml 可序列化类,其中包含一些默认格式的元数据列表。

在算法类中,也有这三个Generic Type Parameters, 我有一个 Base 类型的属性

   public KeyValuePairParserBase<TKey,TValue,TSerialized> Parser {get;set;}

当尝试这样做时

 Parser = new KeyValuePairParser<TKey,TValue>();

编译器声称类型不匹配

我错过了什么?

我们将不胜感激!

环境:Windows 8.1 .NET 4.5.1、C#、VS 2013

【问题讨论】:

    标签: c# xml generics inheritance polymorphism


    【解决方案1】:

    我最终将 KeyValuPairList 和 KeyValuePairParser 的使用推迟到继承类,这解决了问题。

    【讨论】:

      【解决方案2】:

      如果看实例类的定义:

       class KeyValuePairParser<TKey,TValue>
          : KeyValuePairParserBase<TKey, TValue,KeyValuePairList<TKey,TValue>>
      

      你会看到你只有 2 个类型参数:TKey 和 TValue

      但字段

      private KeyValuePairParserBase<TKey,TValue,TSerialized> Parser {get;set;}
      

      定义了三个类型参数:TKey、TValue和TSerialized。

      你必须像这样定义这个字段:

      private KeyValuePairParserBase<TKey,TValue, KeyValuePairList<TKey,TValue>> Parser {get;set;}
      

      一切都会正确的。

      【讨论】:

      • 如果我在 Algorithm 类中定义这样的字段,那么我将强制开发人员从 KeyvaluePairList 继承以添加他们自己的元数据类型,这不是我的目标......我误会你了?
      • 您将强制开发人员使用 KeyValuePairList 作为第三类参数(TSerialized)。否则,您将无法将新类的实例分配给该字段。如果您打算使用所有三个参数,则必须更改 KeyValuePairParser 的继承以支持所有三个类型参数。
      • 我最终将 KeyValuePairList 的使用推迟到继承实现类,这解决了问题!
      猜你喜欢
      • 2020-01-06
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多