声明匿名类型成员用一个简单的名字

声明匿名类型成员用一个简单的名字

本文介绍了声明匿名类型成员用一个简单的名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您尝试进行编译:

var car = new { "toyota", 5000 };

您将得到编译器错误的无效的匿名类型成员声明匿名类型成员必须是用构件分配,简单的名称或成员访问声明。的,因为编译器不能够推断从相应表达式属性的名称。 这非常有意义。

You will get the compiler error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access." because the compiler is not able to infer the name of the properties from the respective expressions. That makes total sense.

是什么让我好奇的是,错误消息意味着三个有效的方法来声明一个类型的成员。成员分配和成员访问是显而易见的:

What makes me curious is that the error message implies three valid ways to declare a type member. Member assignment and member access are obvious:

// member assignment
var v = new { Amount = 108, Message = "Hello" };

// member access
var productQuery =
    from prod in products
    select new { prod.Color, prod.Price };



会是怎样用的简单的名称的声明的例子吗?

谷歌搜索和SO的相关问题导致的例子的成员分配的和的成员访问的唯一。

Googling and the related questions on SO result in examples of member assignment and member access only.

推荐答案

据我所知,简单的名称的声明是这样的:

As far as I know, simple name declaration is this:

var amount = 10;
var whatever = "hello";

var newType = { amount, whatever }



这将自动创建一个匿名类型等于:

Which will automatically create an anonymous type equal to:

var newType = { amount = amount, whatever = whatever }

这篇关于声明匿名类型成员用一个简单的名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:23