السلام عليكــم ورحمـة الله وبركاتــه ،،
هذا الموضوع لتوضيح كيفية عمل Property indexing:
تميزت لغة السي شارب عن باقي اللغات في أمور شتى ومنها كون ان الصفات تأخذ كود لتنفيذه كأنها ميثود
مثال على ذلك
private int prop = 0;
public int Prop
{
get
{
//Executed When the user want the value of this property
return prop;
}
set
{
//Executed When the user assign value to this property
prop = value;//which the user assign to this property
}
}الكود الذي بداخل جملة get يتم تنفيذه عندما يطلب المستخدم قيمة الصفة مثل int x = Prop;
الكود الذي بداخل جملة set يتم تنفيذه عندما يقوم المستخدم باعطاء قيمة لهذه الصفة مثل Prop = 10;
ومن فوائد هذه الطريقة عمل صفات غير قابلة للتغير والتي تسمى Read only property مثل
public int Prop
{
get
{
//Executed When the user want the value of this property
return prop;
}
}لاحظ اننا حذفنا جملة set
مقدمة لعمل indexing
في البداية نحن نعرف عمل المصفوفات وكيف نستعلم عن العناصر التي بها وهو كالتالي
int[] Array = new int[5]; Array[0] = 10;//we use [] for indexing
ولكن الامر الجيد أن في السي شارب ال Indexing ممكن لأي شيئ قابل للعد
مثال على استخدام ال Indexing
public class GroupItem
{
private List<string> Names = new List<string>();
/// <summary>
/// return the name at this index
/// </summary>
public string this[int index] //لاحظ كيفية كتابة هذه الصيغة
{
get { return Names[index]; }
set { Names[index] = value; }
}
/// <summary>
/// return the index of this name
/// </summary>
public int this[string name] //لاحظ كيفية كتابة هذه الصيغة
{
get { return Names.IndexOf(name); }
}
public void AddName(string Name)
{
Names.Add(Name);
}
}
class Program
{
static void Main(string[] args)
{
GroupItem group = new GroupItem();
group.AddName("Ashraf");
group.AddName("Adham");
group.AddName("Ahmad");
group[0] = "Akram"; //لاحظ ان الكلاس اصبح كانه مصفوفة من نوع نص
string x = group[1];
}
}