[英]What is the "with" operator for in C#?
我遇到了這個代碼:
var rectangle = new Rectangle(420, 69);
var newOne = rectangle with { Width = 420 }
我想知道 C# 代碼中的with
關鍵字。 它是做什么用的? 以及如何使用它? 它給語言帶來了什么好處?
它是表達式中使用的運算符,用於更輕松地復制對象,用表達式覆蓋它的一些公共屬性/字段(可選) - 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
}
就它帶來的好處而言,我認為現在應該很明顯了,它使復制實例變得更加容易和方便。
基本上, with
運算符將創建一個新的對象實例(目前僅記錄),通過“處理值”從“源”對象並覆蓋目標對象中的一些命名屬性。
例如,不要這樣做:
var person = new Person("John", "Doe")
{
MiddleName = "Patrick"
};
var modifiedPerson = new Person(person.FirstName, person.LastName)
{
MiddleName = "William"
};
你可以這樣做:
var modifiedPerson = person with
{
MiddleName = "Patrick"
};
基本上,您將編寫更少的代碼。
簡短的回答是: with
在C#關鍵字是對復雜物體,更容易的副本,添加,有可能重寫某些公共屬性的。 已接受的答案中已經簡要提供了示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.