我有一個帶有接口 IDialogueAnimation 的公共類打字機。在 DialoguePrinter 類的方法中,我獲取了具有 IDialogueAnimation 接口的所有對象。它們以類型的形式出現,我想將它們轉換為 IDialogueAnimation。但是,它不會讓我收到“InvalidCastException:指定的轉換無效”。錯誤。為什么是這樣?謝謝!我已經檢查過 Typewriter 和 IDialogueAnimation 是否位于同一個程序集中(這是我嘗試搜索解決方案時出現的問題)。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貢獻1998條經驗 獲得超6個贊
你的item
變量是類型Type
。您無法將 a 強制轉換Type
為您的接口,因為該類Type
沒有實現您的接口。
您只能將實現接口的類型的實例強制轉換為接口,而不是其Type
本身。
如果您想返回該類型的新實例,可以使用Activator.CreateInstance()
以下方法:
if?(item.Name.ToLower()?==?name.ToLower())?{ ????return?(IDialogueAnimation)?Activator.CreateInstance(item); }
如果類型的構造函數需要參數,那么您還需要為構造函數傳遞參數。就像是:
return?(IDialogueAnimation)?Activator.CreateInstance(item,?something,?something);
- 1 回答
- 0 關注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消