无法从System.Collections.Generic.List转换为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这样的值传递。这样您就不必进行投射。