访问 C# 匿名类型对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/713521/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:11:40  来源:igfitidea点击:

Accessing C# Anonymous Type Objects

c#anonymous-types

提问by Ali Kazmi

How do i access objects of an anonymous type outside the scope where its declared?

我如何访问声明范围之外的匿名类型的对象?

for e.g.

例如

void FuncB()
{
var obj = FuncA();
Console.WriteLine(obj.Name);
}

??? FuncA()
{
var a = (from e in DB.Entities
where e.Id == 1
select new {Id = e.Id, Name = e.Name}).FirstOrDefault();

return a;
}

采纳答案by LukeH

As the other answers have stated, you really shouldn't do this. But, if you insist, then there's a nasty hack known as "cast by example" which will allow you to do it. The technique is mentioned in a couple of articles, hereand here.

正如其他答案所说,你真的不应该这样做。但是,如果你坚持,那么有一个被称为“实例化”的讨厌的黑客,它可以让你做到这一点。此处此处的几篇文章中提到了该技​​术。

public void FuncB()
{
    var example = new { Id = 0, Name = string.Empty };

    var obj = CastByExample(FuncA(), example);
    Console.WriteLine(obj.Name);
}

private object FuncA()
{
    var a = from e in DB.Entities
            where e.Id == 1
            select new { Id = e.Id, Name = e.Name };

    return a.FirstOrDefault();
}

private T CastByExample<T>(object target, T example)
{
    return (T)target;
}

(I can't take the credit for this hack, although the author of one of those articles says that he doesn't want to be associated with it either. His name might be familiar.)

(虽然其中一篇文章的作者说他也不想与之相关联,但我不能将这次黑客行为归功于此。他的名字可能很熟悉。)

回答by Paul Suart

You can't return an anonymous type from a function.

您不能从函数返回匿名类型。

From the MSDN documentation:

MSDN 文档

To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

要在方法边界之外传递匿名类型或包含匿名类型的集合,您必须首先将类型强制转换为对象。然而,这打败了匿名类型的强类型。如果您必须存储查询结果或将它们传递到方法边界之外,请考虑使用普通命名结构或类而不是匿名类型。

回答by Anton Gogolev

Anonymous type is just a compiler-generated class, and the compiler is not willing to tell you the name of the class itself. Therefore, there's no way you can return an instance of this class from a function other than returning a reference to an object.

匿名类型只是编译器生成的类,编译器不愿意告诉你类本身的名称。因此,除了返回对object.

回答by bruno conde

Well, I think the answer is: Don't use an anonymous type outside the scope where its declared. In this case create a simple type.

好吧,我认为答案是:不要在声明的范围之外使用匿名类型。在这种情况下,创建一个简单类型。

回答by DayChucatiny

would create a class for this case:

将为这种情况创建一个类:

public class LISTFUNCA   
{                         
    public int identificacion;  
    public string nombre;      
}     

then:

然后:

public List<LISTFUNCA> FuncA()   
{                                          
    var lista = (from e in DB.Entities where e.Id == 1                        
                select new { identificacion = e.Id, nombre = e.Name})
                .FirstOrDefault();  
    return lista.ToList(); 
}     

回答by Richard Anthony Hein

If you are using .NET 4.0, you can use Tuples for this, you'd return a Tuple<int, string>. You can implement your own Tuples for 2.0/3.5, and actually other people already have, so you should be able to do that if you like.

如果您使用 .NET 4.0,您可以为此使用元组,您将返回一个Tuple<int, string>. 您可以为 2.0/3.5 实现自己的元组,实际上其他人已经拥有了,所以如果您愿意,您应该可以这样做。

回答by jbtule

The open source framework Impromptu-Interfacewill allow you to duck cast an anonymous object to an interface. It has the advantage of being less hacky because it will work as expected across assembly boundaries. It accomplishes this using a lightweight proxy and the dlr.

开源框架Impromptu-Interface将允许您将匿名对象转换为接口。它的优点是不那么笨拙,因为它可以跨程序集边界按预期工作。它使用轻量级代理和 dlr 来实现这一点。