如何使用具有泛型参数的类型作为约束?

时间:2008-09-29 18:01:36

标签: c# generics constraints

我想指定一个带有泛型参数的另一种类型的约束。

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

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

但是这还不能在c#中完成,(我真的怀疑它会永远存在)。有没有优雅的解决方案,而不必指定关键帧参数的类型?:

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

4 个答案:

答案 0 :(得分:2)

由于TimeLine很可能是KeyFrames的聚合,所以不会像:

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

很好地满足您的要求?

答案 1 :(得分:2)

Eric Lippert's blog了解详情 基本上,您必须找到一种方法来引用所需的类型,而无需指定辅助类型参数。

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

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>>()

希望有所帮助, 特洛伊

答案 2 :(得分:0)

如果Timeline<T>所代表的类型T与KeyFrame<T>所代表的类型相同,则可以选择:

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

  ...
}

如果类型T表示类之间存在不同的含义,这意味着Timeline<T>可以包含多种类型的KeyFrame,在这种情况下,您应该创建KeyFrame的更抽象的实现并使用那个在Timeline<T>

答案 3 :(得分:0)

Timeline中嵌套KeyFrame可能会对你的设计有意义:

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

  class Timeline<U> where U : Keyframe<T> { 
  } 
} 
相关问题