【问题标题】:C# type cast exception for anonymous type, why? [duplicate]匿名类型的 C# 类型转换异常,为什么? [复制]
【发布时间】:2019-06-05 08:17:59
【问题描述】:

我有一个非常简单的代码 sn-p:

    public static object ParseData(string s)
    {
        string[] array = s.Split(' ');
        return new { Name = array[0], Address = array[1], Postcode = array[2] };
    }

    static T Cast<T>(object obj, T type)
    {
        return (T)obj;//throws exception!
    }
    public static void Main(string[] args)
    {
        string s = "john, 20st, 100020";
        var o = Cast(ParseData(s), new { Name="", Address="", PostCode="" });
    }

运行时,打印异常信息:

Unhandled Exception: System.InvalidCastException: 
Unable to cast object of type 
'<>f__AnonymousType0`3[System.String,System.String,System.String]'
to type
'<>f__AnonymousType1`3[System.String,System.String,System.String]'.

at ConsoleApp1.Program.Cast[T](Object obj, T type) 

为什么会这样,如何修复我的代码?

【问题讨论】:

  • 不要尝试在方法之间传递匿名类型——它们不是为此而设计的。编写自己的类,或使用 ValueTuple
  • @TimSchemelter,我不确定您是否看到重复的答案提供了问题中的代码
  • 这些对象相等:Postcode PostCode .这不是重复的,这是一个错字
  • 无论如何,我不会因为拼写错误而重新打开它。
  • @HimBromBeere Nah,如果我认为值得,我会重新打开

标签: c# types casting anonymous


【解决方案1】:

类型不是具体的。它们现在的形状相同,但这是巧合。在为具体类构建数据时,我尝试只使用匿名类型作为中间步骤,并且匿名类型很少离开单个方法的范围。

匿名类型难以测试,难以传递,而且正如您所发现的,难以转换。

我有时会使用匿名类型从 Web api 方法返回数据,因此当响应序列化为 JSON 时,请赋予其特定形状。然而,消费者通常是一个 JS 客户端,并且不依赖于 C# 类型、匿名或具体来将 JSON 反序列化为对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2011-04-19
    相关资源
    最近更新 更多