【问题标题】:Cannot implicitly cast type - .NET Core [duplicate]无法隐式转换类型 - .NET Core [重复]
【发布时间】:2021-11-11 13:22:35
【问题描述】:

我有一个返回列表列表的 kafka 类,但是当我去的时候,我无法启动它。

public IList<IList<SCP.Kafka.AvroSchemas.historicalDataMeasurementInfo>> equipments
{
    get
    {
        return this._equipments;
    }
    set
    {
        this._equipments = value;
    }
}

为了初始化它,我使用

response.historicalDataMeasurement.equipments = new  List<List<historicalDataMeasurementInfo>>();

但我收到以下错误

无法将类型“System.Collections.Generic.List>”隐式转换为“System.Collections.Generic.IList>”。是否有明确的演员表(是否缺少演员表?)

当我尝试执行时,很快就会得到一个空实例:

response.historicalDataMeasurement.equipments.Add(historicalDataList);

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    您可以使用以下方法对其进行初始化:

    response.historicalDataMeasurement.equipments = new  List<IList<historicalDataMeasurementInfo>>()
    

    请注意,它是IList 中的List

    【讨论】:

      【解决方案2】:

      如果您将 IList 更改为 IEnumerable,如下所示,您也可以创建对象。

      public IEnumerable<IList<SCP.Kafka.AvroSchemas.historicalDataMeasurementInfo>> equipments
      {
          get
          {
              return this._equipments;
          }
          set
          {
              this._equipments = value;
          }
      }
      

      初始化它:

      response.historicalDataMeasurement.equipments = new  List<List<historicalDataMeasurementInfo>>();
      

      【讨论】:

        【解决方案3】:

        看来您的麻烦是因为您需要在列表中转换项目类型。 为此,您可以使用 LINQ 扩展。

        using System.Linq;
        
        // ...
        
        yourList
            .Cast<IList<SCP.Kafka.AvroSchemas.historicalDataMeasurementInfo>>()
            .ToList();
        

        调用Cast&lt;T&gt; 会将您的列表更改为IEnumerable&lt;T&gt;,这就是为什么需要调用ToList() 才能将其更改回列表。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-11-06
          • 2011-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-11
          相关资源
          最近更新 更多