很抱歉地说,但您不能将方法范围外的匿名类型返回。
这是另一种方式来获得anonmous型
// Method that returns anonymous type as object
object ReturnAnonymous()
{
return new { City="Prague", Name="Tomas" };
}
// Application entry-point
void Main()
{
// Get instance of anonymous type with 'City' and 'Name' properties
object o = ReturnAnonymous();
// This call to 'Cast' method converts first parameter (object) to the
// same type as the type of second parameter - which is in this case
// anonymous type with 'City' and 'Name' properties
var typed = Cast(o, new { City="", Name="" });
Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}
// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
return (T)obj;
}
你可以用它仅适用于一个组件类型(来自两个不同的组件两个匿名类型将在内部被编译成两个不同的类型,而且不能使用这个技巧进行转换)。
Dup:http://stackoverflow.com/questions/1070526/how-to-return-anonymous-type-from-c-method-that-uses-linq-to-sql-closed – Krunal 2010-06-30 12:29:44
@Krunal - 那一个作为我使用的那个的副本关闭。 – ChrisF 2010-06-30 12:32:16
@ChrisF - 是的,知道的。但让OP看到一切。 – Krunal 2010-06-30 12:34:10