匿名类型VS局部变量,何时应该使用?

Ali*_*Ali 4 .net c#

我不确定何时应该在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
Run Code Online (Sandbox Code Playgroud)

我应该使用:

var msg = new { 
sender = GetMessagePart(fullMessage, "from")
recipient = GetMessagePart(fullMessage, "to")
};
Run Code Online (Sandbox Code Playgroud)

代替?

Mar*_*ell 8

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

C#匿名类型有2个问题:

  • 你不能通过方法API公开它们
  • 你不能改变它们(成员是只读的)

如果您只需要了解单个方法中的数据,并且它是只读的,那么匿名类型就很方便(实际上这涵盖了很多情况).

如果您需要改变数据或将其传递给调用者,则使用定制类或简单变量(等).

在给出的情况下,我看不出使用匿名类型的理由; 如果您只想要这些值,请使用单独的变量方法.如果"消息"具有已定义的含义,则声明一个Message类并填充该类.