想要通过与类的静态成员进行比较来检查类的类型

本文关键字:比较 检查 类型 静态成员 | 更新日期: 2023-09-27 18:06:38

我有一个父类Command,它有一个const名称和一个名为execute的虚拟方法;两者都被儿童覆盖了。我有一个方法,它接受一个命令列表,并返回一个可能修改过的命令列表。

为了确定是否需要更改输入命令列表,在更改该列表之前,我需要知道列表中每个命令的类型。问题是,我必须使用new关键字,以便为派生类创建一个与父类同名的静态成员,但我希望能够静态引用命令的名称。

我想做的例子:

public List<Command> ReplacementEffect(List<Command> exChain)
{
    for(int index = 0; index < exChain.Count; index++)
    {
         if(exChain[index].Name == StaticReference.Name)
         {
             //Modify exChain here
         }
    }
    return exChain;
}

使用exChain[index]. gettype()的问题是,我必须实例化该类型的另一个对象,只是为了检查哪个是浪费的,耗时的,不直观。另外,我必须从Name中删除const修饰符。

编辑:

class Command
{
    public const string Name = "Null";
    public virtual void Execute()
    {
        //Basic implementation
    }
}
class StaticReference : Command
{
    public new const string Name = "StaticRef";
    public override void Execute()
    {
        //New implementation
    }
}

想要通过与类的静态成员进行比较来检查类的类型

如果你真的不能使用类型比较exChain[index].GetType() == typeof(StaticReference),因为派生类都是StaticReference类型,但你想通过Name来区分(在你的例子中没有显示-但如果不是这种情况,使用类型比较代替),你可以为名称使用静态属性,但通过虚拟访问器访问它:

class Command
{
    public const string Name = "Null";
    public virtual string CommandName
    {
        get
        {
            return Name;
        }
    }
}
class StaticReference : Command
{
    public new const string Name = "StaticRef";
    public virtual string CommandName
    {
        get
        {
            return Name;
        }
    }
}

用法:

     if(exChain[index].CommandName == StaticReference.Name)
     {
         //Modify exChain here
     }