无法从 System.Collections.Generic.List 转换为 System.Collections.Generic.IEnumerable

cannot convert from System.Collections.Generic.List to System.Collections.Generic.IEnumerable

知道为什么我会收到此错误吗?我以为 List 实现了 IEnumerable.

        var customization = new List<CustomerOrderCustomizationDTO>();

        customization.Add(new CustomerOrderCustomizationDTO()
        {
            ProductCustomizationID = _uow.Product.GetCustomization("LENGTH").ID,
            Value = length.ToString()
        });

        customization.Add(new CustomerOrderCustomizationDTO()
        {
            ProductCustomizationID = _uow.Product.GetCustomization("WIDTH").ID,
            Value = width.ToString()
        });

        customization.Add(new CustomerOrderCustomizationDTO()
        {
            ProductCustomizationID = _uow.Product.GetCustomization("WEIGHT").ID,
            Value = weight.ToString()
        });

        return _uow.Product.GetProductPrice(productID, ref customization); //ERROR

界面

decimal GetProductPrice(int productID, ref IEnumerable<CustomerOrderCustomizationDTO> custOrderCustomizations);

因为 custOrderCustomizations 是一个 ref 参数,这意味着参数类型 (IEnumerable) 必须可分配给您传入的变量类型。在这种情况下,您正在传递 customization 变量,它是一个 List。您不能将 IEnumerable 分配给 List.

一个解决方案是将您的 customization 变量分配给类型为 IEnumerable 的新变量并将其传递给 GetProductPrice,如下所示:

IEnumerable<CustomerOrderCustomizationDTO> tempCustomizations = customization;
return _uow.Product.GetProductPrice(productID, ref tempCustomizations);

当您使用 ref 时,它有点像 C++ 中的指针。也就是说,类型必须匹配,而不是可遗传的。您需要将 customization 转换为 IEnumerable<CustomerOrderCustomizationDTO> 才能通过 ref。您可以阅读有关 ref 关键字 here.

的更多信息

您可以删除 ref,因为 List<> 是引用类型,不像 int 那样按值传递。那你就不用投了。