【发布时间】: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