What is the quot;withquot; operator for in C#?(在C#中,quot;和quot;运算符的作用是什么?)
本文介绍了在C#中,";和";运算符的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到此代码:
var rectangle = new Rectangle(420, 69);
var newOne = rectangle with { Width = 420 }
我想知道C#代码中的with关键字。这是做什么用的?怎样才能用得上呢?它给语言带来了什么好处?
推荐答案
它是表达式中使用的运算符,用于简化对象的复制,覆盖对象的某些公共属性/字段(可选) with expression - MSDN
目前只能与记录一起使用。但未来可能不会有这样的限制(假设)。
这里有一个使用示例:
// Declaring a record with a public property and a private field
record WithOperatorTest
{
private int _myPrivateField;
public int MyProperty { get; set; }
public void SetMyPrivateField(int a = 5)
{
_myPrivateField = a;
}
}
现在让我们看看如何使用with运算符:
var firstInstance = new WithOperatorTest
{
MyProperty = 10
};
firstInstance.SetMyPrivateField(11);
var copiedInstance = firstInstance with { };
// now "copiedInstance" also has "MyProperty" set to 10 and "_myPrivateField" set to 11.
var thirdCopiedInstance = copiedInstance with { MyProperty = 100 };
// now "thirdCopiedInstance " also has "MyProperty" set to 100 and "_myPrivateField" set to 11.
thirdCopiedInstance.SetMyPrivateField(-1);
// now "thirdCopiedInstance " also has "MyProperty" set to 100 and "_myPrivateField" set to -1.
MSDN引用类型说明:
可以通过修改记录类型的复制构造函数来修改该逻辑。MSDN报价:对于引用类型成员,复制操作数时仅复制对成员实例的引用。复制操作数和原始操作数都可以访问相同的引用类型实例。
默认情况下,复制构造函数是隐式的,即编译器生成的。如果需要自定义记录复制语义,请显式声明具有所需行为的复制构造函数。
protected WithOperatorTest(WithOperatorTest original)
{
// Logic to copy reference types with new reference
}
至于它有什么好处,我想现在应该很明显了,它使实例的复制变得更加容易和方便。
这篇关于在C#中,";和";运算符的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:在C#中,";和";运算符的作用是什么?
基础教程推荐
猜你喜欢
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
