无法转换对象匿名通用列表

时间:2019-01-25 22:21:40

标签: c# .net asp.net-mvc casting

如果您有任何想法要枚举对象列表,请告诉我。这是它的创建方式。由于某种原因,我无法将其强制转换为List,IList,Enumerable,IEnumerable。我猜是因为它是由第三方创建的。只是看看是否有人有任何想法。

错误如下:

Unable to cast object of type '<>f__AnonymousType5`1[System.Collections.Generic.List`1[SugarRest.Model.AMP_Product_Line]]' to type 'System.Collections.Generic.List`1[SugarRest.Model.AMP_Product_Line]'.

对象创建如下:

private static AMP_Contract CreateCrmContract(ContractDetailViewModel model, int bookmanContractNumber, int renewedFromContractNumber)
        {
            List<AMP_Product_Line> productLines = CreateProductLinesPrint(model, bookmanContractNumber);

            //Contract
            AMP_Contract ampContract = new AMP_Contract();

            ...

            ampContract.amp_amp_contracts_amp_amp_product_lines = new { productLines };

            return ampContract;
        }

public class AMP_Contract
    {              
        ...
        public object amp_amp_contracts_amp_amp_product_lines { get; set; }
        ...
    }

我尝试访问/枚举的对象如下:

vc

enter image description here

我也尝试过此操作,但是,该对象不可枚举,因为它是一个对象。

enter image description here

2 个答案:

答案 0 :(得分:5)

首先,要编写此代码的人正在积极尝试阻止您访问该集合。您应该认真思考是否应该挫败他们的企图。他们可能将其隐藏是有原因的。

最简单的方法是使用dynamic从匿名类型中读取值。然后,您可以动态转换为所需的序列类型:

var contract = CreateCrmContract(...whatever...);
dynamic d = contract.amp_amp_contracts_amp_amp_product_lines;
IEnumerable<AMP_Product_Line> lines = d.productLines;

现在我们回到了静态类型的世界:

foreach (AMP_Product_Line line in lines)
  Console.WriteLine(line);

答案 1 :(得分:1)

您必须为此编写一个方法

public static object ToNonAnonymousList<T>(this List<T> list, Type t)
{

   //define system Type representing List of objects of T type:
   var genericType = typeof(List<>).MakeGenericType(t);

   //create an object instance of defined type:
   var l = Activator.CreateInstance(genericType);

   //get method Add from from the list:
   MethodInfo addMethod = l.GetType().GetMethod("Add");

   //loop through the calling list:
   foreach (T item in list)
   {

      //convert each object of the list into T object 
      //by calling extension ToType<T>()
      //Add this object to newly created list:
      addMethod.Invoke(l, new object[] { item.ToType(t) });
   }

   //return List of T objects:
   return l;
}

使用

var genericType = typeof(List<>).MakeGenericType(t);

例如查看

https://www.codeproject.com/Articles/38635/Converting-anonymous-types-to-any-type

相关问题