将子类别与父类别区分开来

时间:2019-01-30 11:10:04

标签: c# list inheritance parent-child

我需要在父母名单中区分孩子。 我有一个父母名单

class Example
{
    JsonPatchOperation AddRelationship(JsonPatchDocument doc, string rel, WorkItem linkedItem, bool isNew, int index)
    {
        //update link
        if (!isNew)
        {
            return new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/relations/" + index,
                Value = new { rel, url = linkedItem.Url, attributes = new { comment = "comment while update" } }
            };
        }
        else
            return new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/relations/-",
                Value = new { rel, url = linkedItem.Url, attributes = new { comment = "Comment while creating item" } }
            };
    }

    void Save()
    {
        // some code
        doc.Add(AddRelationship(doc, "System.LinkTypes.Hierarchy-Forward", item, isNew, index++));

        var workItem = isNew
                     ? witClient.CreateWorkItemAsync(doc, Vsts.Project, issueType, bypassRules: true, validateOnly: Mode == ProcessingMode.ReadOnly).Result
                     : witClient.UpdateWorkItemAsync(doc, existingWorkItemId.Value, bypassRules: true, validateOnly: Mode == ProcessingMode.ReadOnly).Result;

    }
}

是否可以检查列表中的项目是Child1还是Child2?

2 个答案:

答案 0 :(得分:0)

不清楚是要知道这些项目是全部特定类型还是这两种类型之一。

要确定是否所有项目都是Child1实例:

all.All(item => (item is Child1))

要确定所有项目是Child1还是Child2实例:

all.All(item => (item is Child1) || (item is Child2))

答案 1 :(得分:0)

如果您要遍历列表并根据商品类型执行某些操作,则可以执行以下操作:

> ar
, , lev

      col col_1 col_2
row     1     5     9
row_1   2     6    10
row_2   3     7    11
row_3   4     8    12

, , lev_1

      col col_1 col_2
row    13    17    21
row_1  14    18    22
row_2  15    19    23
row_3  16    20    24

如果使用c#7,则可以通过直接在if语句中创建一个临时变量来做得更好:

foreach(var item in list)
{
    if(item is Child1)
    {
        var child1 = (Child1)item;
        child1.DoSomething();
    }
    else if(...)
    {
        ...
    }
}

或者您可以使用foreach(var item in list) { if(item is Child1 child1) { child1.DoSomething(); } else if(...) { ... } } 运算符,如下所示:

as