简体   繁体   English

C#列表,Foreach和类型

[英]C# Lists, Foreach, and Types

I was wondering if there is a version of foreach that checks only for a specific type and returns it. 我想知道是否有foreach版本仅检查特定类型并返回它。

For example consider this class tree: 例如,考虑此类树:

org.clixel.ClxBasic -> org.clixel.ClxObject -> org.clixel.ClxSprite -> WindowsGame1.test org.clixel.ClxBasic-> org.clixel.ClxObject-> org.clixel.ClxSprite-> WindowsGame1.test

Then consider this code 然后考虑这段代码

public List<ClxBasic> objects = new List<ClxBasic>();

foreach(GroupTester tester in objects)
{
    tester.GroupTesterOnlyProperty = true;
}

tester.GroupTesterOnlyProperty is a property created in GroupTester. tester.GroupTesterOnlyProperty是在GroupTester中创建的属性。 Is there some way to make something like this work, like an overload of foreach, or another snippet that might help me? 有什么办法可以使类似的工作,例如foreach的重载,或者其他可以帮助我的代码段? I want to make it easy for a programmer to sort through the lists grabbing only what type they need. 我想让程序员轻松排序列表,仅获取他们需要的类型。

You can use the OfType<T> extension method for IEnumerable<T> objects. 您可以对IEnumerable<T>对象使用OfType<T>扩展方法。

Your loop could then look like this: 然后,您的循环可能如下所示:

foreach(GroupTester tester in objects.OfType<GroupTester>())
{
    tester.GroupTesterOnlyProperty = true;
}

Note: This assumes that GroupTester inherits from ClxBasic . 注意:这假定GroupTester继承自ClxBasic

foreach(GroupTester tester in objects.OfType<GroupTester>())
{
    tester.GroupTesterOnlyProperty = true;
}

As suggested by @ThePower (and then deleted), you could iterate over all objects and check the type explicitly: 如@ThePower所建议(然后删除),您可以遍历所有对象并显式检查类型:

foreach(var tester in objects)
{
    if (tester is GroupTester)
    {
       (tester as GroupTester).GroupTesterOnlyProperty = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM