使用反射,我得到了程序集中的所有类型.如果我知道它实现了接口"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)