簡體   English   中英

嘗試將Type強制轉換為接口時,為什么會收到“ InvalidCastException:指定的強制轉換無效”的信息

[英]Why am I getting an “InvalidCastException: Specified cast is not valid.” when trying to cast a Type to interface

我有一個帶有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);

}

您的item變量的類型為Type 您不能將Type為接口,因為Type不能實現您的接口。

您只能將實現您的接口的類型的實例強制轉換為接口,而不是Type本身。

如果要返回該類型的新實例,可以使用Activator.CreateInstance()來執行以下操作:

if (item.Name.ToLower() == name.ToLower()) {
    return (IDialogueAnimation) Activator.CreateInstance(item);
}

如果類型的構造函數需要參數,則還需要為構造函數傳遞參數 就像是:

return (IDialogueAnimation) Activator.CreateInstance(item, something, something);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM