آشنایی با مفهوم Indexer در C#.NET
نویسنده: علیرضا اسمرام
تاریخ: ۱۳۹۱/۰۴/۲۰ ۱۹:۵۶
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public type this [type identifier]
{
get{ ... }
set{ ... }
}
public class Matrix
{
// فیلدها
private int _row, _col;
private readonly double[,] _values;
// تعداد ردیفهای ماتریس
public int Row
{
get { return _row; }
set
{
_row = value > 0 ? value : 3;
}
}
// تعداد ستونهای ماتریس
public int Col
{
get { return _col; }
set
{
_col = value > 0 ? value : 3;
}
}
// نعریف یک ایندکسر
public double this[int r, int c]
{
get { return Math.Round(_values[r, c], 3); }
set { _values[r, c] = value; }
}
// سازنده 1
public Matrix()
{
_values = new double[_row,_col];
}
// سازنده 2
public Matrix(int row, int col)
{
_row = row;
_col = col;
_values = new double[_row,_col];
}
}
public class UseMatrixIndexer
{
// ایجاد نمونه از شیء ماتریس
private readonly Matrix m = new Matrix(5, 5);
private double item;
public UseMatrixIndexer()
{
// دسترسی به عنصر واقع در ردیف چهار و ستون سه
item = m[4, 3];
}
}
using System;
namespace IndexedProperties
{
public class Data
{
private int[] _localArray;
private ArrayIndexer _arrayIndexer;
public Data()
{
_localArray = new int[10];
for (int i = 0; i < 10; i++)
_localArray[i] = i + 1;
_arrayIndexer = new ArrayIndexer(this);
}
public ArrayIndexer Number
{
get { return _arrayIndexer; }
}
public class ArrayIndexer
{
private Data _arrayOwner;
public ArrayIndexer(Data arrayOwner)
{
_arrayOwner = arrayOwner;
}
public int this[int index]
{
get { return _arrayOwner._localArray[index]; }
}
public int Length
{
get { return _arrayOwner._localArray.Length; }
}
}
}
class Program
{
static void Main(string[] args)
{
var data = new Data();
for (int i = 0; i < 10; i++)
Console.WriteLine(data.Number[i]);
}
}
}