![](/img/trans.png)
[英]Checking if an object implements an interface with a generic <T> where the generic type is a child of T
[英]Why can't I cast an item to a generic type — where the generic type is an interface, and after checking that the item implements said interface?
我正在嘗試為我的游戲編寫效果(à la buffs/debuffs)。 這是我想要構建的:
EffectsManager
類包含所有活動效果。 像HealthController
這樣的類會查詢與健康相關的效果,即實現IHealthEffect
接口的效果,並返回一個僅包含此類效果的 List。
內部EffectsManager
:
public List<T> GetEffects<T>() {
List<T> effects = new List<T>();
foreach (ActiveEffect activeEffect in activeEffects) {
// ActiveEffect is just a wrapper for Effect that houses duration, time elapsed, etc.
// I only need to return the Effect itself, which houses the logic.
Effect effect = activeEffect.GetEffect();
if (effect is T) {
effects.Add((T)effect);
}
}
return effects;
}
然后,調用者腳本會寫:
List<IHealthEffect> healthEffects = effectsManager.GetEffects<IHealthEffect>();
無法將類型“效果”轉換為“T”
在effects.Add((T)effect);
.
但就我而言,我不是在進行隱式轉換,而是進行顯式轉換。 為什么編譯器不讓我繼續,我應該使用Convert.ChangeType()
- 正如那里建議的那樣 - 無論如何?
Effect
只是一個抽象類,只有 1 個成員: public int priority;
.
由於一個效果可能會影響多個屬性,例如健康和法力,我決定使用要求實現者編寫特定方法的接口,例如: void Execute(HealthController healthController);
.
干得好:
if (effect is T typed) {
effects.Add(typed);
}
至於為什么:你需要在中間投射一個object
: (T)(object)effect
但就我而言,我不是在進行隱式轉換,而是進行顯式轉換。
Effect
和T
無關,因此編譯器將嘗試轉換而不是強制轉換,並且顯然也沒有在類型之間定義轉換,因此會出現錯誤。
正如 Marc 所建議的,您可以充分利用模式匹配:
if (effect is T t) {
effects.Add(t);
}
但是,如果您的代碼與發布的完全一樣,則可以完全通過 LINQ 實現:
var healthEffects = activeEffects.Select(x => x.GetEffect()).OfType<IHealthEffect>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.