C# 匿名类型问题
在下面的代码中,为什么变量 c2 和 c3 是不同的匿名类型?
预先感谢您的任何建议和...干杯!
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var c1 = new Customer { Name = "Mark", Country = "USA" };
var c2 = new { c1.Name, c1.Country }; //"<>f__AnonymousType0`2"
var c3 = new { c1.Country, c1.Name }; //"<>f__AnonymousType1`2"
}
}
public class Customer
{
public string Name { get; set; }
public string Country { get; set; }
}
}
In the following code why are the variables c2 and c3 of a different anonymous type?
Thanks in advance for any advice and ... cheers !
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var c1 = new Customer { Name = "Mark", Country = "USA" };
var c2 = new { c1.Name, c1.Country }; //"<>f__AnonymousType0`2"
var c3 = new { c1.Country, c1.Name }; //"<>f__AnonymousType1`2"
}
}
public class Customer
{
public string Name { get; set; }
public string Country { get; set; }
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您以不同的顺序初始化了它们的属性。
如果您以相同的顺序初始化它们,它们只会被编译为相同的匿名类型。来自关于匿名类型的 MSDN 文档:
Because you initialized their properties in different orders.
They'll only be compiled to the same anonymous type if you initialize them in the same order. From the MSDN docs on anonymous types: