Menu
CoddyTech

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

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

ל-C אין בקרת גישה על איברי מבנה: כל קוד שרואה את ההגדרה יכול להקצות ישירות ערך ל-account.amount, ולכן ספריות C מסתירות את המצב מאחורי מצביע אטום ופונקציות getter כגון account_balance. ב-C# השדה נשאר private, ונחשף מאפיין שקוראים קוראים כמו שדה, בעוד שה-accessor קובע מה מותר. מאפיין עם getter בלבד מספק גישת קריאה כמו פונקציית getter ב-C, ומשאיר כל עדכון מאחורי מתודות שמאמתות אותו.

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

הפניה ל-C

#include <stdio.h>

struct Account { int amount; };

static void account_init(struct Account *a, int n) { a->amount = n > 0 ? n : 0; }
static void account_deposit(struct Account *a, int n) { if (n > 0) a->amount += n; }
static int account_balance(const struct Account *a) { return a->amount; }

int main(void) {
    struct Account account;
    account_init(&account, 5);
    account_deposit(&account, -3);
    printf("%d\n", account_balance(&account));
    account.amount = -100;   /* עובר קומפילציה: שום דבר לא מסתיר את השדה */
    printf("%d\n", account_balance(&account));
    return 0;
}

הצהרות עזר ב-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
-100

פלט 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# אונליין