我无法将一个匿名类型转换为另一个匿名类型。我想知道为什么。无法将一个匿名类型转换为另一个匿名类型
public static class Class1{
public static object GetFinance(Guid contractB2CId)
{
return new
{
Item1 = reader.ValueOrDefault<decimal>(0),
Item2 = reader.ValueOrDefault<decimal>(1),
Item3 = reader.ValueOrDefault<decimal>(2),
Item4 = reader.ValueOrDefault<decimal>(3),
Item5 = reader.ValueOrDefault<decimal>(4),
Item6 = reader.ValueOrDefault<decimal>(5)
};
}
object obj = GetFinance();
var financeInfo = obj.UnsafeCast(new
{
Item1 = default(decimal),
Item2 = default(decimal),
Item3 = default(decimal),
Item4 = default(decimal),
Item5 = default(decimal),
Item6 = default(decimal)
});
}
public static class Class2{
public static T UnsafeCast<T>(this object obj, T type)
{
return (T) obj;
}
}
异常
无法转换 类型“<> f__AnonymousType1
6[System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal]' to type '<>f__AnonymousType0
6 [System.Decimal,System.Decimal,System.Decimal,System.Decimal,System.Decimal,系统的目的.Decimal]”。
UPDATE: 有什么办法避免这种例外,除了使用Tuple<decimal.....>
或使用一个组装?
我的代码位于不同的程序集中。我认为这是例外的原因。 – Alexandre
如果这些类型在同一个程序集中,那么这个类型是多余的,所以是的。但是,除非你正在施放对象或其他重复施放(施放为相同类型),否则使用匿名类型施放时将失去运气 –
@Alex如果它位于不同的装配体中,则我知道***它是原因。匿名类型的类型等价只适用于同一个程序集。考虑使用一个命名类型 - 也许是'Tuple.Create(...)'等 –