【问题标题】:Access item properties in an array of different types访问不同类型数组中的项目属性
【发布时间】:2019-10-08 13:40:59
【问题描述】:

我调用了两种不同的方法,它们返回了一个不同类型的列表。然后我将这些列表组合成一个数组,从而创建一个包含两种不同类型对象的数组。现在我正在尝试使用foreach 循环遍历该数组,但是对于数组中的每个项目,我需要访问它的唯一属性。有没有办法做到这一点?

List<TypeA> typeAVariable = SomeMethod();
List<TypeB> typeBVariable = AnotherMethod();

var arr = new ArrayList();
arr.AddRange(typeAVariable);
arr.AddRange(typeBVariable);

foreach(var item in arr)
{
    if(item.typeOf == typeAVariable)
    {
        item.typeAVariableProperty;
    }
    else
    {
        item.typeBVariableProperty;
    }

}

【问题讨论】:

  • 为什么需要将它们合并到一个列表中?为什么不使用两个 foreach 循环,每个列表一个?
  • 是否需要访问每种类型的多个属性,这些属性是相同类型还是相似类型?
  • @ChetanRanpariya 我想将它们结合起来,这样我就可以使用更少的代码(例如,一个 foreach 循环而不是两个)。
  • @Terence 我需要访问每个属性的两个属性。

标签: c# arraylist


【解决方案1】:

如果你真的需要将不同类型的项目组合成废弃ArrayList集合(List&lt;Object&gt;是更好的选择),你可以试试pattern匹配 得到itemAitemB 返回:

foreach(var item in arr) 
{
    if (item is TypeA itemA)
    {
        itemA.typeAVariableProperty;
    }
    else if (item is TypeB itemB) 
    {
        itemB.typeBVariableProperty;
    }
}

【讨论】:

  • 谢谢!
【解决方案2】:

我想我会使用as 来转换你的对象,然后再检查它是否为空。像这样:

foreach(var item in arr)
{
    var convertedItem = item as typeAVariable;
    if(convertedItem == null)
    {
        // Do what you need for B type
        (typeBVariable)item.typeBVariableProperty;
        continue;
    } 
    // Do what you need for A type
    convertedItem.typeAVariableProperty;

}

【讨论】:

    【解决方案3】:

    创建一个(抽象的)基类并让两个类都继承自基类。然后创建一个可以包含这两种类型的List&lt;BaseClass&gt;

    abstract class BaseClass
    {
    }
    
    class TypeA : BaseClass
    {
        public int AnIntroperty { get; set; }
    }
    
    class TypeB : BaseClass
    {
        public string AStringroperty { get; set; }
    }
    

    然后像这样使用它:

    List<TypeA> typeAVariable = SomeMethod();
    List<TypeB> typeBVariable = AnotherMethod();
    
    var combinedList = List<BaseClass>();
    combinedList.AddRange(typeAVariable);
    combinedList.AddRange(typeBVariable);
    
    foreach (var item in combinedList)
    {
        if (item is TypeA typeAItem)
        {
            typeAItem.AnIntroperty;
        }
        else if (item is TypeB typeBItem)
        {
            typeBItem.AStringroperty;
        }
    }
    

    【讨论】:

      【解决方案4】:

      你可以这样写:

      switch (item)
      {
          case TypeA typeA:
              typeA.typeAVariableProperty
              // do sth
              break;
      
          case TypeB typeB:
              typeB.typeBVariableProperty
              // do sth
              break;
      }
      

      Switch 语句可以比 if-else 结构更快。见:Is there any significant difference between using if/else and switch-case in C#?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多