c# - 丢弃和不分配变量有什么区别?
问题描述
在 c# 7.0 中,您可以使用丢弃。使用丢弃和简单地不分配变量有什么区别?
public List<string> DoSomething(List<string> aList)
{
//does something and return the same list
}
_ = DoSomething(myList);
DoSomething(myList);
有什么区别吗?
解决方案
两条代码行之间绝对没有区别。
它们都转换为完全相同的 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 的评论之后更新:
请注意,我仅指的是这种特定情况。
当按预期使用时,丢弃可以节省内存和/或提高代码的可读性。
推荐阅读
- c - 当 x 是有符号整数且 x=1 时,找到一个值 y,例如 (x < y) == (-x > -y) 将是假的?
- python - 使用 pyparsing 解析可变数量的可选参数
- javascript - 对象是不可迭代的 JavaScript
- ios - 从一组颜色中选择一种随机颜色以在 SwiftUI 的视图中使用
- python-3.x - 机器人框架 - 新标签问题
- javascript - 语法错误:标识符“i”已被声明为 JavaScript
- echarts - 在 echarts 中,有没有办法在没有格式化程序的情况下将 xAxis 上的格式“时间”设置为指定的时区?
- pandas - 使用 pandas groupby 绘制散点图进行跟踪
- visual-studio-code - 如何在 vscode 终端中使用 git bash 别名?
- android - Kotlin 片段:尝试在空对象引用上调用虚拟方法“java.lang.String android.content.Context.getPackageName()”