我有一個(gè)帶有接口 IDialogueAnimation 的公共類打字機(jī)。在 DialoguePrinter 類的方法中,我獲取了具有 IDialogueAnimation 接口的所有對象。它們以類型的形式出現(xiàn),我想將它們轉(zhuǎn)換為 IDialogueAnimation。但是,它不會(huì)讓我收到“InvalidCastException:指定的轉(zhuǎn)換無效”。錯(cuò)誤。為什么是這樣?謝謝!我已經(jīng)檢查過 Typewriter 和 IDialogueAnimation 是否位于同一個(gè)程序集中(這是我嘗試搜索解決方案時(shí)出現(xiàn)的問題)。IDialogueAnimation GetAnimationInterfaceFormName(string name){ Type parentType = typeof(IDialogueAnimation); Assembly assembly = Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes(); IEnumerable<Type> imp = types.Where(t => t.GetInterfaces().Contains(parentType)); foreach (var item in imp) { if (item.Name.ToLower() == name.ToLower()) { return (IDialogueAnimation) item; } } Debug.LogError("Can't find any animation with name " + name); return null;}這是界面public interface IDialogueAnimation{ bool IsPlaying { get; set; } IEnumerator Run(OrderedDictionary wordGroup, float speed);}
1 回答
米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
你的item變量是類型Type。您無法將 a 強(qiáng)制轉(zhuǎn)換Type為您的接口,因?yàn)樵擃?code>Type沒有實(shí)現(xiàn)您的接口。
您只能將實(shí)現(xiàn)接口的類型的實(shí)例強(qiáng)制轉(zhuǎn)換為接口,而不是其Type本身。
如果您想返回該類型的新實(shí)例,可以使用Activator.CreateInstance()以下方法:
if?(item.Name.ToLower()?==?name.ToLower())?{
????return?(IDialogueAnimation)?Activator.CreateInstance(item);
}如果類型的構(gòu)造函數(shù)需要參數(shù),那么您還需要為構(gòu)造函數(shù)傳遞參數(shù)。就像是:
return?(IDialogueAnimation)?Activator.CreateInstance(item,?something,?something);
- 1 回答
- 0 關(guān)注
- 223 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
