在 C# 中返回匿名类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10073319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning anonymous type in C#
提问by frenchie
I have a query that returns an anonymous type and the query is in a method. How do you write this:
我有一个返回匿名类型的查询,并且该查询在一个方法中。你怎么写这个:
public "TheAnonymousType" TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return "TheAnonymousType";
}
}
采纳答案by abatishchev
You can't.
你不能。
You can only return object, or container of objects, e.g. IEnumerable<object>, IList<object>, etc.
你只能返回object,或物体的容器,例如IEnumerable<object>,IList<object>等等。
回答by Justin Pihony
You cannot return anonymous types. Can you create a model that can be returned? Otherwise, you must use an object.
您不能返回匿名类型。你能创建一个可以退货的模型吗?否则,您必须使用object.
Here is an article written by Jon Skeet on the subject
这是乔恩·斯基特 (Jon Skeet) 撰写的关于该主题的文章
Code from the article:
文章中的代码:
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
Or, here is another similar article
Or, as others are commenting, you could use dynamic
或者,正如其他人评论的那样,您可以使用 dynamic
回答by Chuck Norris
You can return list of objects in this case.
在这种情况下,您可以返回对象列表。
public List<object> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB ;
}
}
回答by Not loved
You can return dynamicwhich will give you a runtime checked version of the anonymous type but only in .NET 4+
您可以返回dynamic,这将为您提供匿名类型的运行时检查版本,但仅限于 .NET 4+
回答by Ivo
Three options:
三个选项:
Option1:
选项1:
public class TheRepresentativeType {
public ... SomeVariable {get;set;}
public ... AnotherVariable {get;set;}
}
public IEnumerable<TheRepresentativeType> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
Option 2:
选项 2:
public IEnumerable TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
you can iterate it as object
您可以将其作为对象进行迭代
Option 3:
选项 3:
public IEnumerable<dynamic> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB; //You may need to call .Cast<dynamic>(), but I'm not sure
}
}
and you will be able to iterate it as a dynamic object and access their properties directly
并且您将能够将其作为动态对象进行迭代并直接访问它们的属性
回答by Bastardo
public List<SomeClass> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new SomeClass{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB.ToList();
}
}
public class SomeClass{
public string SomeVariable{get;set}
public string AnotherVariable{get;set;}
}
Creating your own class and querying for it is the best solution I know.As much as I know you can not use anonymous type return values in another method, because it won't just be recognized.However, they can be used in the same method.
I used to return them as IQueryableor IEnumerable, though it still does not let you see what is inside of the anonymous type variable.
创建你自己的类并查询它是我知道的最好的解决方案。据我所知,你不能在另一个方法中使用匿名类型的返回值,因为它不会被识别。但是,它们可以在同一个方法中使用方法。我曾经将它们作为IQueryableor返回IEnumerable,尽管它仍然不让您看到匿名类型变量的内部内容。
I run into something like this before while I was trying to refactor some code, you can check it here : Refactoring and creating separate methods
我之前在尝试重构一些代码时遇到过这样的事情,你可以在这里查看:重构和创建单独的方法
回答by Sandeep
C# compiler is a two phase compiler. In the first phase it just checks namespaces, class hierarchies, Method signatures etc. Method bodies are compiled only during the second phase.
C# 编译器是一个两阶段编译器。在第一阶段,它只检查命名空间、类层次结构、方法签名等。方法主体仅在第二阶段编译。
Anonymous types are not determined until the method body is compiled.
在编译方法体之前不会确定匿名类型。
So the compiler has no way of determining the return type of the method during the first phase.
所以编译器在第一阶段没有办法确定方法的返回类型。
That is the reason why anonymous types can not be used as return type.
这就是匿名类型不能用作返回类型的原因。
As others have suggested if you are using .net 4.0 or grater, you can use Dynamic.
正如其他人所建议的,如果您使用的是 .net 4.0 或更高版本,则可以使用Dynamic.
If I were you I would probably create a type and return that type from the method. That way it is easy for the future programmers who maintains your code and more readable.
如果我是你,我可能会创建一个类型并从方法中返回该类型。这样一来,未来的程序员就可以轻松维护您的代码并且更具可读性。
回答by craigrs84
You can use the Tuple class as a substitute for an anonymous types when returning is necessary:
当需要返回时,您可以使用 Tuple 类代替匿名类型:
Note: Tuple can have up to 8 parameters.
注意:元组最多可以有 8 个参数。
return Tuple.Create(variable1, variable2);
Or, for the example from the original post:
或者,对于原始帖子中的示例:
public List<Tuple<SomeType, AnotherType>> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select Tuple.Create(..., ...)
).ToList();
return TheQueryFromDB.ToList();
}
}
http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
回答by Rosdi Kasim
In C# 7 we can use tuples to accomplish this:
在 C# 7 中,我们可以使用元组来实现这一点:
public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB
.Select(s => (
SomeVariable = s.SomeVariable,
AnotherVariable = s.AnotherVariable))
.ToList();
}
}
You might need to install System.ValueTuplenuget package though.
不过,您可能需要安装System.ValueTuplenuget 包。
回答by Imran Jalali
You can only use dynamic keyword,
您只能使用动态关键字,
dynamic obj = GetAnonymousType();
Console.WriteLine(obj.Name);
Console.WriteLine(obj.LastName);
Console.WriteLine(obj.Age);
public static dynamic GetAnonymousType()
{
return new { Name = "John", LastName = "Smith", Age=42};
}
But with dynamic type keyword you will loose compile time safety, IDE IntelliSense etc...
但是使用动态类型关键字,您将失去编译时安全性、IDE IntelliSense 等...

