我不确定什么时候应该在 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
我应该使用:
var msg = new {
sender = GetMessagePart(fullMessage, "from")
recipient = GetMessagePart(fullMessage, "to")
};
代替?
最佳答案
你是指静态类型变量吗?请注意,匿名类型是静态类型...(由于问题编辑而删除)
C# 匿名类型有两个问题:
- 您不能通过方法 API 公开它们
- 你不能改变它们(成员是只读的)
如果您只需要了解单个方法中的数据,并且它是只读的,那么匿名类型就很方便(实际上这涵盖了很多情况)。
如果您需要改变数据或将其传递给调用者,请使用定制类或简单变量(等)。
在给定的情况下,我看不到使用匿名类型的理由;如果您只想要这些值,请使用单独的变量方法。如果“消息”具有定义的含义,则声明一个 Message
类并填充它。
关于c# - 匿名类型 VS 局部变量,什么时候应该使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/527685/