【发布时间】: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?
【问题讨论】: