代码之家  ›  专栏  ›  技术社区  ›  Melody

Visual Studio不会在类型检查后推断变量的类型

  •  -3
  • Melody  · 技术社区  · 2 年前

    我正在循环浏览 List<CComponent> (CComponent是我的类),并且只想在继承自 CPowerable 类(继承自CComponent)。问题是,几乎永远不会有一个基本的CPowerable元素,而且通常只有从中继承的元素。所以如果我这样做了 foreach (CPowerable i in list) ,那将把他们全部投给CPowerable。

    当我添加一个类型检查时,改为如下所示:

    foreach (CComponent i in neighbours)
    {
        if(i.GetType().IsSubclassOf(typeof(CPowerable)))
        {
            i.powerSources.Add(this);
            i.updateNode(this, this, false);
        } else
        {
            continue;
        }
    }
    

    Visual Studio给了我 this ,当代码将在其上运行的所有元素都将继承CPowerable,并因此具有这些字段时。 我如何让编译器知道所有这些对象都将继承CPowerable?

    1 回复  |  直到 2 年前
        1
  •  1
  •   ProgrammingLlama Raveena Sarda    2 年前

    您可以对此使用模式匹配:

    foreach (CComponent i in neighbours)
    {
        if(i is CPowerable powerableI)
        {
            powerableI.powerSources.Add(this);
            powerableI.updateNode(this, this, false);
        }
    }
    

    请注意 else 具有 continue; 不需要,因为循环中没有其他内容。

    或者,您可以包括 using System.Linq; 在代码文件的顶部,然后使用 .OfType<CPowerable>() :

    foreach (var i in neighbours.OfType<CPowerable>())
    {
        i.powerSources.Add(this);
        i.updateNode(this, this, false);
    }