在C#中表达类型关系并避免长类型参数列表

时间:2013-03-21 12:05:42

标签: c# generics type-parameter

我有这种情况(大大简化):

interface IPoint<TPoint> 
   where TPoint:IPoint<TPoint>
{
   //example method
   TPoint Translate(TPoint offset);
}

interface IGrid<TPoint, TDualPoint> 
   where TPoint:IPoint<T
   where TDualPoint:Ipoint
{
   TDualPoint GetDualPoint(TPoint point, /* Parameter specifying direction */);
}

这是典型的实施:

class HexPoint : IPoint<HexPoint> { ... }
class TriPoint : IPoint<TriPoint> { ... }

class HexGrid : IGrid<HexPoint, TriPoint> { ... }
class TriGrid : IGrid<TriPoint, HexPoint> { ... }

所以在HexGrid上,客户端可以调用双网格获得一个点,具有完全正确的类型:

TriPoint dual = hexGrid.GetDualPoint(hexPoint, North);

到目前为止一切顺利;客户不需要知道关于两点如何相关的类型,她需要知道的是HexGrid方法GetDualPoint返回TriPoint

...除

我有一个充满通用算法的类,它在IGrid上运行,例如:

static List<TPoint> CalcShortestPath<TPoint, TDualPoint>(
   IGrid<TPoint, TDualPoint> grid, 
   TPoint start, 
   TPoint goal) 
{...}

现在,客户端突然必须知道HexPoint的双重点是TriPoint的细节,我们需要将其指定为类型参数列表的一部分,即使它这个算法并不严格:

static List<TPoint> CalcShortestPath<TPoint, *>(
   IGrid<TPoint, *> grid, 
   TPoint start, 
   TPoint goal) 
{...}

理想情况下,我想将DualPoint设为IPoint类型的“属性”,以便HexPoint.DualPoint 类型为TriPoint

允许IGrid看起来像这样的东西:

interface IGrid<TPoint> 
   where TPoint:IPoint<TPoint> 
   //and TPoint has "property" DualPoint where DualPoint implements IPoint...
{
   IGrid<TPoint.DualPoint> GetDualGrid();
}

和函数CalcShortestPath一样

static List<TPoint> CalcShortestPath<TPoint>(
   IGrid<TPoint> grid, 
   TPoint start, 
   TPoint goal) 
{...}

当然,据我所知,这是不可能的。

但有没有办法可以改变我的设计以模仿这种方式?那么

  • 它表达了两种类型之间的关系
  • 它可以防止过多的类型参数列表
  • 它可以防止客户端过分思考具体类型如何“专门化”类型实现的接口的类型参数。

要说明为什么这会成为一个真正的问题:在我的库中IGrid实际上有4个类型参数,IPoint有3个,两者都可能增加(最多6个和5个)。 (大多数这些类型参数之间存在类似的关系。)

算法的显式重载而不是泛​​型是不切实际的:IGridIPoint各有9个具体实现。一些算法在两种类型的网格上运行,因此具有一吨类型参数。 (许多函数的声明比函数体长!)

当我的IDE在自动重命名期间丢弃所有类型参数时,心理负担被驱逐回家了,我不得不手动将所有参数放回去。这不是一个无意识的任务;我的大脑被炸了。


根据@Iridium的要求,显示何时类型推断失败的示例。显然,下面的代码没有做任何事情;它只是为了说明编译器的行为。

using System;
using System.Collections.Generic;
using System.Linq;

public interface IPoint<TPoint, TDualPoint> 
   where TPoint:IPoint<TPoint, TDualPoint> 
   where TDualPoint : IPoint<TDualPoint, TPoint>{}

interface IGrid<TPoint, TDualPoint> 
   where TPoint:IPoint<TPoint, TDualPoint>
   where TDualPoint:IPoint<TDualPoint, TPoint>{}

class HexPoint : IPoint<HexPoint, TriPoint> 
{
   public HexPoint Rotate240(){ return new HexPoint();} //Normally you would rotate the point
}

class TriPoint : IPoint<TriPoint, HexPoint>{}    
class HexGrid : IGrid<HexPoint, TriPoint>{}

static class Algorithms
{  
   public static IEnumerable<TPoint> TransformShape<TPoint, TDualPoint>(
      IEnumerable<TPoint> shape, 
      Func<TPoint, TPoint> transform)

   where TPoint : IPoint<TPoint, TDualPoint> 
   where TDualPoint : IPoint<TDualPoint, TPoint> 
   {
      return 
         from TPoint point in shape
            select transform(point);
   }

   public static IEnumerable<TPoint> TransformShape<TPoint, TDualPoint>(
      IGrid<TPoint, TDualPoint> grid, 
      IEnumerable<TPoint> shape, 
      Func<TPoint, TPoint> transform)

   where TPoint : IPoint<TPoint, TDualPoint> 
   where TDualPoint : IPoint<TDualPoint, TPoint> 
   {
      return 
         from TPoint point in shape
            //where transform(point) is in grid
            select transform(point);
   }
}

class UserCode
{  
   public static void UserMethod()
   {
      HexGrid hexGrid = new HexGrid();      
      List<HexPoint> hexPointShape = new List<HexPoint>(); //Add some items

      //Compiles
      var rotatedShape1 = Algorithms.TransformShape(
         hexGrid,
         hexPointShape, 
         point => point.Rotate240()).ToList();

      //Compiles   
      var rotatedShape2 = Algorithms.TransformShape<HexPoint, TriPoint>(
         hexPointShape, 
         point => point.Rotate240()).ToList(); 

      //Does not compile   
      var rotatedShape3 = Algorithms.TransformShape(
          hexPointShape, 
          point => point.Rotate240()).ToList();
   }
}

2 个答案:

答案 0 :(得分:2)

我曾遇到泛型过载的情况,其中我有一组5个通用接口,并且每个接口根据通用接口的每个实现进行参数化。这在理论上是一个很棒的设计,因为它意味着静态检查所有方法参数和返回类型。

实际上,在与该设计争论一段时间之后,并意识到这意味着任何将这些接口作为参数的任何方法必须指定所有类型参数,我决定简单地使这些接口非泛型并使用运行时强制转换来获取方法参数,而不是让编译器强制执行它。

我建议简化设计 - 最多可能从接口中删除所有类型参数。

根据您要定义的算法类型,可能的解决方案可能是定义额外的接口,这些接口采用较少的类型参数,并且在交换中暴露较少的方法。

e.g:

interface IPoint 
{
    int X {get;}
    int Y {get;}
    // Maybe you do not need that one.
    IPoint Translate(IPoint dual);
}
interface IPoint<TPoint> : IPoint
    where TPoint : IPoint<TPoint>
{
    new TPoint Translate(TPoint dual);
}

现在,您可以定义一个算法,该算法在没有关于双点类型泄漏的信息的情况下采用IPoint。但请注意,对同一事物使用通用和非通用接口可能会使设计更加复杂。

如果没有关于真实界面的更多信息,以及您需要如何使用它,我真的不知道建议的精确修改。

不要忘记你应该平衡实现的复杂性和可读性 - 即使你在重写方法类型参数时遇到困难,也要考虑那些没有编写它们就会使用你的对象的人!

答案 1 :(得分:2)

所以,根据我在评论中谈到的一次性想法,我会提出一个答案......

基本要点是“定义一种传达这种点对偶概念的类型,并在相关的签名中使用它,以便为编译器提供所需的提示”

每当你点击可怕的“无法从使用中推断出类型”错误时,你应该阅读的一件事: http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

在那,Messr。 Lippert阐述了在这个推理阶段只检查签名参数的严酷事实,而不是约束。所以我们必须在这里更加“具体”。

首先,让我们来定义我们的“二元关系” - 我应该注意到这是建立这些关系的单向,理论上它们是无限多种。

public interface IDual<TPoint, TDualPoint> 
    where TPoint: IPoint<TPoint>, IDual<TPoint, TDualPoint>
    where TDualPoint: IPoint<TDualPoint>, IDual<TDualPoint, TPoint>
{}

现在我们回过头来改造我们现有的签名:

public interface IPoint<TPoint> 
   where TPoint:IPoint<TPoint> 
{}
class TriPoint : IPoint<TriPoint>, IDual<TriPoint,HexPoint>
{}
class HexPoint : IPoint<HexPoint>, IDual<HexPoint,TriPoint> 
{
   // Normally you would rotate the point
   public HexPoint Rotate240(){ return new HexPoint();} 
}

同样在“次要类型”上,网格:

interface IGrid<TPoint, TDualPoint> 
   where TPoint: IPoint<TPoint>, IDual<TPoint, TDualPoint>  
   where TDualPoint : IPoint<TDualPoint>, IDual<TDualPoint, TPoint> 
{
    TDualPoint GetDualPoint(TPoint point);
}
class HexGrid : IGrid<HexPoint, TriPoint>
{
    public TriPoint GetDualPoint(HexPoint point)
    {
        return new TriPoint();
    }
}
class TriGrid : IGrid<TriPoint, HexPoint> 
{
    public HexPoint GetDualPoint(TriPoint point)
    {
        return new HexPoint();
    }
}

最后我们的实用方法:

static class Algorithms
{  
   public static IEnumerable<TPoint> TransformShape<TPoint, TDualPoint>(
      IEnumerable<IDual<TPoint, TDualPoint>> shape, 
      Func<TPoint, TPoint> transform)
   where TPoint : IPoint<TPoint>, IDual<TPoint, TDualPoint>   
   where TDualPoint : IPoint<TDualPoint>, IDual<TDualPoint, TPoint> 
   {
      return 
         from TPoint point in shape
            select transform(point);
   }

   public static IEnumerable<TPoint> TransformShape<TPoint, TDualPoint>(
      IGrid<TPoint, TDualPoint> grid, 
      IEnumerable<IDual<TPoint, TDualPoint>> shape, 
      Func<TPoint, TPoint> transform)
   where TPoint : IPoint<TPoint>, IDual<TPoint, TDualPoint>   
   where TDualPoint : IPoint<TDualPoint>, IDual<TDualPoint, TPoint> 
   {
      return 
         from TPoint point in shape
            //where transform(point) is in grid
            select transform(point);
   }
}

注意方法上的签名 - 我们说“嘿,这个我们给你的东西列表,它绝对有双点”,这就是允许这样的代码:

  HexGrid hexGrid = new HexGrid();      
  List<HexPoint> hexPointShape = new List<HexPoint>(); //Add some items

  //Compiles
  var rotatedShape1 = Algorithms
      .TransformShape(
     hexGrid,
     hexPointShape, 
     point => point.Rotate240())
    .ToList();

  //Compiles   
  var rotatedShape2 = Algorithms
      .TransformShape<HexPoint, TriPoint>(
     hexPointShape, 
     point => point.Rotate240())
    .ToList();     

  //Did not compile, but does now!
  var rotatedShape3 = Algorithms
      .TransformShape(
      hexPointShape, 
      point => point.Rotate240())
    .ToList();