第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

為什么我收到“InvalidCastException:指定的轉(zhuǎn)換無效。” 當(dāng)嘗試將類型轉(zhuǎn)換為接口時(shí)

為什么我收到“InvalidCastException:指定的轉(zhuǎn)換無效。” 當(dāng)嘗試將類型轉(zhuǎn)換為接口時(shí)

C#
青春有我 2023-07-09 14:57:58
我有一個(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);


查看完整回答
反對 回復(fù) 2023-07-09
  • 1 回答
  • 0 關(guān)注
  • 223 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)