我有一个非常简单的代码段:
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)
为什么会这样,如何修复我的代码?
类型不是具体的。它们现在是相同的形状,但这是一个巧合。在为具体类建立数据时,我尝试仅将匿名类型用作中介步骤,并且匿名类型很少离开单个方法的范围。
匿名类型很难测试,难以传递,而且正如您所发现的那样,很难转换。
有时我会使用匿名类型从Web api方法返回数据,因此在将响应序列化为JSON时赋予其特定的形状。但是,使用者通常将是JS客户端,并且不依赖于C#类型(匿名或具体)将JSON反序列化为对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句