[英]Allow all types of generic types in a List
我在使用泛型時遇到了一些問題。 我有一個稱為動畫的基類,從該基類可以派生不同類型的動畫(例如,double,vector等),並且為了處理所有動畫,我使用靜態類來基本上管理所有動畫。
public class Animation<T>
{
public virtual Action<T> UpdateAction { get; set; }
public EasingFunctionBase EasingFunction { get; set; }
private TimeSpan _Duration = TimeSpan.FromMilliseconds(0);
public TimeSpan Duration { get; set; }
public T currentValue { get; internal set; }
internal TimeSpan CurrentTime = TimeSpan.FromMilliseconds(0);
internal double Percentage = 0;
internal bool HasFinished = false;
internal virtual void Update()
{
UpdateAction?.Invoke(CurrentValue);
}
public virtual void BeginAnimation()
{
if (Duration.TotalMilliseconds <= 0)
throw new InvalidOperationException("You need a duration greater than 0 seconds.");
AnimationFactory.BeginAnimation(this);
}
}
DoubleAnimation : Animation<double>
{
*do some calculations and set currentValue*
}
public static class AnimationFactory
{
private static List<Animation> _CurrentAnimations = new List<Animation>();
public static void BeginAnimation<T>(Animation<T> animation)
{
// Here is where I'm getting the error. I want this list to be able to contain all types of Animation<T>.
_CurrentAnimations.Add(animation);
_isEnabled = true;
}
void Update()
{
for(int i = 0; i < _CurrentAnimations.Count; i++)
{
_CurrentAnimations[i].update();
}
}
}
如您所見,我在將新創建並要運行的動畫添加到列表中時遇到錯誤。 如何使此列表接受各種 Animation<T>
? 還是我要解決這個錯誤? 我添加了通用類型以刪除轉換(如果設置動畫結構),但是也許有一個更聰明的解決方案。
如何使此列表接受各種動畫?
除非Animation
是Animation<T>
的基類,否則不能這樣做。 什么是 Animation
?它與什么Animation<T>
關系 ? 根據您的其他信息,似乎您實際上還沒有Animation
類。
一種選擇是使靜態類也通用,例如AnimationFactory<T>
。 那么列表將是List<Animation<T>>
。 但是對於每個類型參數T
,您將有一個不同的列表,這似乎與您要查找的不一樣。
根據到目前為止的信息,我想說您應該讓Animation<T>
繼承Animation
或其他一些適當的基類(使用該基類作為List<T>
的類型參數)。 在此特定示例中,這將需要創建Animation
基類,因為實際上這還不存在。
除此以外,您的問題可能是XY問題 。 也就是說,您向我們提出了錯誤的問題,因此您應該真正將重點放在您真正要解決的更廣泛的問題上,而不是列表中的具體內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.