首页 > 解决方案 > 丢弃和不分配变量有什么区别?

问题描述

在 c# 7.0 中,您可以使用丢弃。使用丢弃和简单地不分配变量有什么区别?

public List<string> DoSomething(List<string> aList)
{ 
//does something and return the same list
}
_ = DoSomething(myList);
DoSomething(myList);

有什么区别吗?

标签: c#c#-7.0

解决方案


两条代码行之间绝对没有区别。
它们都转换为完全相同的 IL:

public void A(List<string> myList)
{
    _ = DoSomething(myList);
}

public void B(List<string> myList)
{
    DoSomething(myList);
}

两者都翻译为:

IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call instance class [System.Private.CoreLib]System.Collections.Generic.List`1<string> C::DoSomething(class [System.Private.CoreLib]System.Collections.Generic.List`1<string>)
IL_0007: pop
IL_0008: ret

你可以自己看 (注:我实际上看不懂IL,但这是A和B方法的结果)SharpLab

正如利亚姆在他的回答中所写,丢弃对于out您不会使用的参数、元组解构、模式匹配和开关表达式很有用。
您可以在官方文档中阅读所有相关信息。

在 Liam 的评论之后更新: 请注意,我仅指的是这种特定情况。
当按预期使用时,丢弃可以节省内存和/或提高代码的可读性。


推荐阅读