publicvoidChangeName(string newLastName) { // Generates CS0200: Property or indexer cannot be assigned to -- it is read only LastName = newLastName; } }
自动属性初始化
自动属性初始值设定项 可让你在属性声明中声明自动属性的初始值。
1
public ICollection<double> Grades { get; } = new List<double>();
publicstaticasync Task<string> MakeRequestAndLogFailures() { await logMethodEntrance(); var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync("https://localHost:10000"); try { var responseText = await streamTask; return responseText; } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301")) { await logError("Recovered from redirect", e); return"Site Moved"; } finally { await logMethodExit(); client.Dispose(); } }
使用索引器初始化关联集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 原来语法 private Dictionary<int, string> messages = new Dictionary<int, string> { { 404, "Page not Found"}, { 302, "Page moved, but left a forwarding address."}, { 500, "The web server can't come out to play today."} };
// 新语法支持使用索引分配到集合中: private Dictionary<int, string> webErrors = new Dictionary<int, string> { [404] = "Page not Found", [302] = "Page moved, but left a forwarding address.", [500] = "The web server can't come out to play today." };