c# - C# 中的“with”运算符是什么?
问题描述
我遇到了这段代码:
var rectangle = new Rectangle(420, 69);
var newOne = rectangle with { Width = 420 }
我想知道with
C# 代码中的关键字。它是干什么用的?以及如何使用它?它给语言带来了什么好处?
解决方案
它是表达式中使用的运算符,用于更轻松地复制对象,用表达式覆盖它的一些公共属性/字段(可选) - 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
}
就它带来的好处而言,我认为现在应该很明显了,它使复制实例变得更加容易和方便。
推荐阅读
- python - Beautifulsoup 匹配空类
- node.js - 使用nodeJS在Sequelize中创建行后如何重新加载表?
- git - Git 提交被拒绝,但与 --no-verify 一起使用
- rust - 有什么方法可以重用相同的结构,还是我需要在 Rust 中构建一个新结构?
- javascript - 从单选按钮获取值 - "input[name='gender']:checked" 返回 null
- ethereum - 如果客户端没有安装元掩码(或其他),有没有办法从智能合约中读取?
- python - LinkedIn API - 组织品牌有时限仅返回时间范围
- python - 从输入框获取()返回“无”
- java - 使用 Streams 打印 PriorityQueue 的值会产生不正确的结果
- ruby-on-rails - 使用与常规连接不同的用户进行 Rails 迁移