【问题标题】:Why am I getting an "InvalidCastException: Specified cast is not valid." when trying to cast a Type to interface为什么我会收到“InvalidCastException:指定的演员表无效。”尝试将类型转换为接口时
【发布时间】:2019-11-28 22:01:44
【问题描述】:

我有一个带有接口 IDialogueAnimation 的公共类 Typewriter。在 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);

}

【问题讨论】:

    标签: c# interface casting


    【解决方案1】:

    您的item 变量是Type 类型。您不能将Type 强制转换为您的接口,因为Type 类没有实现您的接口。

    您只能将实现您的接口的类型的 instance 转换为接口,而不是 Type 本身。

    如果您想返回该类型的新实例,您可以使用Activator.CreateInstance() 来执行此操作:

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

    如果类型的构造函数需要参数,那么你也需要pass the parameters for the constructor。比如:

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

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多