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

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>,
{
}
有帮助吗?

解决方案

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

希望有所帮助, 特洛伊

其他提示

由于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表示类之间存在不同的含义,这意味着KeyFrame可以包含多种类型的<=>,在这种情况下,您应该创建一个更抽象的<=>实现并在<=>中使用它。

也许嵌套TimelineKeyFrame里面会对你的设计有意义:

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

  class Timeline<U> where U : Keyframe<T> { 
  } 
} 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top