且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中声明匿名类型的LIST变量

更新时间:2022-12-23 10:56:54

就其性质而言,匿名类型不能明确地声明".他们是匿名的,未知的;您没有要声明的类型.这样,匿名类型,无论是直接类型还是通用类型参数,都不能指定为参数,用作返回类型或存储到任何显式类型的变量中.您必须使用var进行分配,这意味着您仅限于在本地范围内使用类型.

Anonymous types, by their very nature, can't be explicitly "declared". They're anonymous, unknown; you don't have a type to declare. As such, anonymous types, whether directly or as a generic type parameter, cannot be specified as parameters, used as a return type, or stored to any explicitly typed variable. You must use var to assign them, and that means you're pretty much limited to using the type in local scope.

基本上,您唯一的选择是将匿名类型转换为可以显式声明的收集类型(即,您必须声明类型本身).只需创建一个简单的DTO类,并在调用ToList之前,通过使用匿名类型初始化您的强类的Select()Linq节点运行匿名类型.

Your only option, basically, is to convert your anonymous type into a collected type that can be explicitly declared (i.e. you must declare the type itself). Just create a simple DTO class, and before calling ToList, run the anonymous type through a Select() Linq node that uses the anonymous type to initialize your strong class.

如果使用的是.NET 4.0,则可以转到dynamic. dynamic关键字以及任何通过参数声明为dynamic的参数或返回类型传递的对象,基本上告诉编译器不要尝试验证对其执行的任何操作.您可以尝试使用任何运算符,调用任何方法等.但是,如果运算符,成员或您执行的任何其他操作对于该对象实际在幕后的内容无效,那么您将获得运行时异常,您必须非常有力地处理.因此,不要轻易使用.NET 4.0的dynamic功能.

If you are using .NET 4.0, you COULD go dynamic. The dynamic keyword, and any object that's been passed through a parameter or return type declared dynamic, basically tells the compiler not to try to verify any operation performed on it; you can try to use any operator, call any method, etc. HOWEVER, if the operator, member, or whatever other operation you are performing isn't valid for what the object actually is behind the scenes, you'll get runtime exceptions which you must handle very robustly. For this reason, the dynamic feature of .NET 4.0 is not to be used lightly.

正如Kratz所说的,您唯一可以做的另一件事就是返回一个ArrayList或一个Object []数组,并使用反射来发现匿名类型的结构.几乎没有任何切分的方法.您会丢失集合的强类型,代码会膨胀,因为您甚至需要几行代码来执行最简单的get或set操作,并且反射的性质,可能比同等操作上的速度慢100倍.已知的静态类型.

The only other thing you can do, as Kratz said, is return an ArrayList, or an Object[] array, and use reflection to discover the anonymous type's structure. It's a no-no pretty much any way you slice it; you lose the strong typing of the collection, your code bloats considerably as you need several lines of code to perform even the simplest get or set operations, and reflection, again by its nature, can be up to 100x slower than the equivalent operation on a known static type.