匿名类型VS局部变量,当人应该被使用? [英] Anonymous types VS Local variables, When should one be used?

查看:162
本文介绍了匿名类型VS局部变量,当人应该被使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道,当我在C#中使用的匿名类型的而不是局部变量的。

I am not sure when I should use anonymous types instead of local variables in C#.

我有:

string  fullMessage // This is the full message including sender and recipient names

string sender = GetMessagePart(fullMessage, "from");
string recipient = GetMessagePart(fullMessage, "to");

//do some stuff and deliver the message

我应该使用:

Should I use:

var msg = new { 
sender = GetMessagePart(fullMessage, "from")
recipient = GetMessagePart(fullMessage, "to")
};

相反?

推荐答案

你的意思是静态类型的变量?需要注意的是匿名类型的的静态类型... (删除,由于问题编辑)

Do you mean statically typed variables? Note that anonymous types are statically typed... (removed due to question edit)

有两个问题用C#匿名类型:

There are 2 problems with C# anonymous types:

  • 您无法通过API的方式暴露它们
  • 您可发生变异他们(成员只读)

如果你只需要知道在一个单一的方法中的数据,它是只读的,那么一个匿名类型是很方便的(这涵盖了很多的情况下,在现实中)。

If you only need to know about the data within a single method, and it is read-only, then an anonymous type is handy (and this covers a lot of cases, in reality).

如果您需要变异数据,或者把它传递出一个来电,然后使用一个定制类,或简单的变量(等)。

If you need to mutate the data or pass it out to a caller, then use either a bespoke class, or simple variables (etc).

在给定的情况下,我看不出一个理由来使用匿名类型;如果你只是想要的值,可以使用单独的变量的方法。如果消息有一个定义的含义,声明消息类和填充的。

In the case given, I can't see a reason to use an anonymous type; if you just want the values, use the separate variable approach. If a "message" has a defined meaning, declare a Message class and populate that.

这篇关于匿名类型VS局部变量,当人应该被使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆