调用未知类类型的方法
本文关键字:方法 类型 未知 调用 | 更新日期: 2023-09-27 18:28:25
我正试图做这样的事情,但我不知道怎么做,我有点迷失了
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;
}
}
我希望能够为从Commands
派生的所有类调用execute()
我怎样才能做到这一点?
更新:我认为最好解释一下我想要归档的内容。当我将类名作为参数传递时,我正试图使类调用成为方法。
我认为您可能有一些一般的设计问题,但编译错误是由于缺少括号。
return ((Commands)type).execute(cmdParams);
点的存在(发生在铸造之前)比铸造更高。
有了完整的报价,您的报价如下:
return (Commands)(type.execute(cmdParams));
其失败,因为它在已知type
的情况下找不到execute
。
还要注意,您可能想了解为什么要查看类型名称,as
和is
更安全、更容易实现。
var command = type as Commands;
if (command != null)
{
return command.execute(cmdParams);
}
else
{
//Command not found!
return 1;
}
看起来您有一个类型的集合,您正试图将其用作实例。您需要一个类型的实例来调用上的非静态方法,这可以通过强制转换或反射来完成。
如果要从类型创建实例,请使用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;
}
}
在尝试调用execute
:之前,您只需要先进行强制转换
return ((Commands)type).execute(cmdParams);
按照您编写它的方式,它试图对未转换的类型调用execute
,然后将结果转换为Commands
。