Menu
CoddyTech

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

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

לטבלאות Luau אין תחביר של מאפיינים: הנוהג המקובל הוא להשתמש בשיטת getter, כגון Balance(), או במטא־שיטות __index ו־__newindex שמיירטות מפתחות חסרים. כל מי שקורא לקוד עדיין יכול להקצות ישירות ל־account._amount, ו־table.freeze חוסמת כתיבה רק לעומק של רמה אחת. מאפיין ב־C# עם getter ציבורי וללא setter ציבורי גורם למהדר לדחות הקצאה מבחוץ. לא table.freeze ולא הפניה readonly ב־C# מקפיאות לעומק מצב מקונן.

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

דוגמה לייחוס ב־Luau

local Account = {}
Account.__index = Account
function Account.new(n: number)
    return setmetatable({ _amount = math.max(0, n) }, Account)
end
function Account:Deposit(n: number)
    if n > 0 then
        self._amount += n
    end
end
function Account:Balance(): number
    return self._amount
end
local account = Account.new(5)
account:Deposit(-3)
print(account:Balance())

הצהרות תומכות ב־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# למפתחי Luau

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