如何使用以通用参数作为约束的类型?

时间:2020-03-06 14:53:16  来源:igfitidea点击:

我想指定一个约束,它是带有通用参数的另一种类型。

class KeyFrame<T>
{
    public float Time;
    public T Value;
}

// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}

但这还不能一而就(我真的很怀疑会如此)。是否有任何优雅的解决方案,而不必指定keyframe参数的类型?:

class Timeline<TKeyframe, TKeyframeValue> 
     where TKeyframe : Keyframe<TKeyframeValue>,
{
}

解决方案

由于TimeLine最有可能是KeyFrames的聚合,因此不会像这样:

class TimeLine<T>
{
private IList<KeyFrame<T>> keyFrameList;
...
}

很好地满足要求?

如果Timeline <T>表示的类型T与KeyFrame <T>表示的类型相同,则可以使用:

class Timeline<T>
{
  List<KeyFrame<T>> _frames = new List<KeyFrame<T>>(); //Or whatever...

  ...
}

如果类型T在类之间表示不同,则意味着"时间线<T>"可以包含多种类型的"键帧",在这种情况下,我们应该创建一个更抽象的"键帧"实现,并在"时间线<T"中使用它>`。

从Eric Lippert的博客中了解有关此内容的信息
基本上,我们必须找到一种无需指定辅助类型参数即可引用所需类型的方法。

在他的帖子中,他显示了此示例作为可能的解决方案:

public abstract class FooBase
{
  private FooBase() {} // Not inheritable by anyone else
  public class Foo<U> : FooBase {...generic stuff ...}

  ... nongeneric stuff ...
}

public class Bar<T> where T: FooBase { ... }
...
new Bar<FooBase.Foo<string>>()

希望能有所帮助,
特洛伊

也许在" KeyFrame"中嵌套" Timeline"在设计中很有意义:

class KeyFrame<T> { 
  public float Time; 
  public T Value; 

  class Timeline<U> where U : Keyframe<T> { 
  } 
}