在C#中返回匿名类型

我有一个返回匿名类型的查询,并且该查询在方法中。你怎么写这个:


public "TheAnonymousType" TheMethod(SomeParameter)

{

  using (MyDC TheDC = new MyDC())

  {

     var TheQueryFromDB = (....

                           select new { SomeVariable = ....,

                                        AnotherVariable = ....}

                           ).ToList();


      return "TheAnonymousType";

    }

}


守着星空守着你
浏览 1941回答 3
3回答

Helenr

你不能你只能返回object,或物体的容器,例如IEnumerable<object>,IList<object>等等

HUH函数

您不能返回匿名类型。您可以创建可以返回的模型吗?否则,您必须使用object。文章中的代码:using System;static class GrottyHacks{&nbsp; &nbsp; internal static T Cast<T>(object target, T example)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (T) target;&nbsp; &nbsp; }}class CheesecakeFactory{&nbsp; &nbsp; static object CreateCheesecake()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new { Fruit="Strawberry", Topping="Chocolate" };&nbsp; &nbsp; }&nbsp; &nbsp; static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; object weaklyTyped = CreateCheesecake();&nbsp; &nbsp; &nbsp; &nbsp; var stronglyTyped = GrottyHacks.Cast(weaklyTyped,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new { Fruit="", Topping="" });&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Cheesecake: {0} ({1})",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stronglyTyped.Fruit, stronglyTyped.Topping);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}或者,正如其他人评论的那样,您可以使用 dynamic
打开App,查看更多内容
随时随地看视频慕课网APP