如何在运行时明确地将类型转换为Interface

Ale*_*eld 0 c# types casting

使用反射,我得到了程序集中的所有类型.如果我知道它实现了接口"ICommand",我如何将Type t转换为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('.'));
    }
 }
Run Code Online (Sandbox Code Playgroud)

我试图投射的类型的一个例子

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Sea*_*ean 7

你试图将t类型转换Type为a ICommand,它没有实现.

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

var obj = Activator.CreateInstance(t);
var C = (ICommand)obj;
Run Code Online (Sandbox Code Playgroud)