小编Ale*_*eld的帖子

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

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

c# types casting

0
推荐指数
1
解决办法
52
查看次数

标签 统计

c# ×1

casting ×1

types ×1