我遇到了這個代碼:
var rectangle = new Rectangle(420, 69);
var newOne = rectangle with { Width = 420 }
我想知道withC# 代碼中的關鍵字。它有什么用?以及如何使用它?它給語言帶來了什么好處?
uj5u.com熱心網友回復:
它是運算式中使用的運算子,用于更輕松地復制物件,用運算式覆寫它的一些公共屬性/欄位(可選) - 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
}
就它帶來的好處而言,我認為現在應該很明顯了,它使復制實體變得更加容易和方便。
uj5u.com熱心網友回復:
基本上,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"
};
基本上,您將撰寫更少的代碼。
使用此來源獲取有關上述示例的更多詳細資訊和更多示例的官方檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323402.html
上一篇:“無法將型別為“Google.Android.Material.TextView.MaterialTextView”的實體轉換為型別“AndroidX.AppCompat.Widget.Toolbar
