【问题标题】:How to explicity cast a type to Interface at runtime如何在运行时将类型显式转换为接口
【发布时间】:2017-12-14 09:43:55
【问题描述】:

使用反射,我得到了程序集中的所有类型。如果我知道 Type t 实现了接口“ICommand”,我该如何将它转换为 ICommand

ICommand C;
foreach(Type t in asm.GetTypes())
{

    if (t.GetInterfaces()[0].Name is "ICommand")
    {
        C = (ICommand)t; //throws Exception here - Unable
                         //to cast to ICommand
       RootDir.AddCommand(C, t.Namespace.Split('.'));
    }
 }

我尝试投射的类型示例

public interface ICommand
{
    string HelpDescription { get; }
    void Execute(CommandClass CC);
}


class CurrentDir : ICommand
{
    public string HelpDescription => "Current Directory - Change current directory";

    public static explicit operator CurrentDir (Type T)
    {
        return new CurrentDir();
    }

    void ICommand.Execute(CommandClass CC)
    {
        throw new NotImplementedException();
    }
}

我应该如何实现它以便它可以从 System.Type 转换为 ICommand?

【问题讨论】:

    标签: c# types casting


    【解决方案1】:

    您正在尝试将 Type 类型的 t 转换为 ICommand,但它没有实现。

    从您的代码外观来看,您需要创建一个 t 的实例,然后对其进行转换:

    var obj = Activator.CreateInstance(t);
    var C = (ICommand)obj;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多