2008-09-29 66 views
2

我想指定一个约束,这是一个泛型参数的另一种类型。如何将具有泛型参数的类型用作约束条件?

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>, 
{ 
} 
+0

你使用的是什么版本的C#...永远不会看到时间轴其中T:关键帧<*> m Ÿ生活 – 2008-09-29 18:05:05

+0

时间轴是一类我自己的:) – Trap 2008-09-29 18:07:05

+0

我想的愿望将有类似于从C++模板,模板类',所以 类时间轴> { } 强制使用的关键帧的任何专业化作为时间轴的约束条件 – workmad3 2008-09-29 18:10:50

回答

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

的类型,不会是这样的:

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

很好地满足你的要求?

0

如果Timeline<T>代表类型T相同KeyFrame<T>代表你可以用走类型:

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

    ... 
} 

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

0

也许筑巢TimelineKeyFrame将使意义,在您的设计:

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

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