Menu
CoddyTech

מאפיינים מגינים על אינווריאנטים

שיעור 34 מתוך 48 בקורס C# למפתחי C++ של Coddy.

בדרך כלל, C++ חושפת שיטת getter מסוג const. ב-C# יש תחביר של מאפיינים שהקוד שקורא להם קורא כמו לשדה, בעוד שמאפי הגישה קובעים את החוזה. גישה ציבורית לקריאה בלבד שומרת את עדכוני היתרה מאחורי שיטות, ללא תלות במודל ניהול הזיכרון השונה.

מאפיינים מספקים גישה מבוקרת, בעוד ששדות פרטיים שומרים על אינווריאנטים. getter יכול להציג מצב בלי לאפשר לקוד שקורא לו להציב ערכים שרירותיים. setter פרטי או מאפיין לקריאה בלבד הם בחירה בחוזה; אל תחשוף שדה שניתן לשינוי כאשר העדכונים דורשים אימות.

דוגמה ב-C++

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Account { int amount; public: explicit Account(int n):amount(max(0,n)) {} void deposit(int n) { if(n>0) amount+=n; } int balance() const { return amount; } };
int main() {
Account account(5); account.deposit(-3); cout << account.balance() << "\n";
}

הצהרות תומכות ב-C#

class Reading { private int raw; public Reading(int raw) { this.raw = raw; } public int Doubled { get { return raw * 2; } } }

פקודות ב-C# בתוך Main

var reading = new Reading(3);
Console.WriteLine(reading.Doubled);

אלה קטעים ממוקדים להוראה. קובצי האתגר כוללים עטיפות מלאות שניתנות להרצה; הקטעים שלמעלה מציגים את ההצהרות והפקודות הרלוונטיות.

פלט לדוגמה:

5

פלט ב-C#:

6
challenge icon

אתגר

קל

מימוש Account מלא: יתרת הפתיחה מוגבלת לאפס לכל הפחות, הפקדות חיוביות מגדילות אותה, והפקדות אפס או שליליות נזנחות. אפשר לקרוא את היתרה, אך לא להגדיר אותה באופן ציבורי.

ערכו את קובצי C# שאינם נעולים. הקובץ הנעול הגלוי Main.cs קורא את השורות המתוארות, קורא ל־Exercise.Solve, מוודא שהקלט לא השתנה ומדפיס את התוצאה עם תו שורה חדשה אחד בסוף. השאירו את ממשקי ה־API המוצהרים. אל תוסיפו Main נוסף ואל תדפיסו פלט אבחוני.

המפעיל הנעול גם בודק באופן עצמאי את ממשק ה־API של פונקציית העזר או המחלקה שיוצאו, ולא רק את מעטפת Solve.

נסו בעצמכם

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var accountOne = new Account(-2); var accountTwo = new Account(5); accountOne.Deposit(3); accountOne.Deposit(-9); if (accountOne.Balance != 3 || accountTwo.Balance != 5) throw new Exception("Account API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה C# למפתחי C++

תרגלו בעצמכם: קומפיילר C# אונליין