调用未知类类型的方法

时间:2013-08-19 22:01:08

标签: c# .net generics

我正在尝试这样做,但我不知道怎么样,我有点失落

    foreach ( var type in cmdTypes )
    {
        if ( type.Name.ToLowerInvariant() == Name.ToLowerInvariant() )
        {
            return (Commands)type.execute(cmdParams);//<==Incorrect

        }
        else
        {
            //Command not found!
            return 1;
        }
    }

此类是Commands的派生。这是基类:

abstract class Commands
{
    internal abstract int execute(object[] myParameters );

    internal string Name;

    public Commands()
    {
        Name=this.GetType().Name;
    }
}

我希望能够为execute()派生的所有类调用Commands 我怎么能做到这一点?

更新:如果我解释一下我要存档的内容,我认为会更好。当我将类名作为参数传递时,我正在尝试将类调用为方法。

3 个答案:

答案 0 :(得分:3)

我认为您可能遇到一些常规设计问题,但编译错误是由于缺少括号。

return ((Commands)type).execute(cmdParams);

Dot比存在更高的存在(发生在之前)。

完整报价如下:

return (Commands)(type.execute(cmdParams));

由于找不到execute的内容,因此无法找到type

另请注意,您可能希望了解查看类型名称的原因,asis更安全,更易于实施。

var command = type as Commands;
if (command != null)
{
    return command.execute(cmdParams);
}
else
{
    //Command not found!
    return 1;
}

答案 1 :(得分:2)

在尝试拨打execute

之前,您只需先进行投射
return ((Commands)type).execute(cmdParams);

你编写它的方式是,它试图在未转换的类型上调用execute,然后将结果转换为Commands

答案 2 :(得分:2)

您似乎有一组 types ,您尝试将其用作实例。您需要一个类型的实例来调用非静态方法,这可以通过强制转换或反射来完成。

如果您想创建该类型的实例,请使用Activator.CreateInstance

foreach ( var type in cmdTypes )
{
    if ( type.Name.ToLowerInvariant() == Name.ToLowerInvariant() )
    {
        Command cmd = Activator.CreateInstance(type) as Command;
        if(cmd != null)  // cmd is a Command!
            return cmd.execute(cmdParams);
        else
            // what should you do?
    }
    else
    {
        //Command not found!
        return 1;
    }
}
相关问题