我知道物业的形式如下:
class MyClass
{
public int myProperty { get; set; }
}这使我可以这样做:
MyClass myClass = new MyClass();
myClass.myProperty = 5;
Console.WriteLine(myClass.myProperty); // 5但是,,我可以做什么以便下面的类:
class MyOtherClass
{
public int[,] myProperty
{
get
{
// Code here.
}
set
{
// Code here.
}
}
}其行为如下:
/* Assume that myProperty has been initialized to the following matrix:
myProperty = 1 2 3
4 5 6
7 8 9
and that the access order is [row, column]. */
myOtherClass.myProperty[1, 2] = 0;
/* myProperty = 1 2 3
4 5 0
7 8 9 */
Console.WriteLine(myOtherClass.myProperty[2, 0]); // 7提前感谢!
发布于 2013-06-11 22:14:38
您可以绕过实际实现该属性,并允许编译器为您使用自动属性;
public class Test
{
// no actual implementation of myProperty is required in this form
public int[,] myProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.myProperty = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Console.WriteLine(t.myProperty[1, 2]);
t.myProperty[1, 2] = 0;
Console.WriteLine(t.myProperty[1, 2]);
}
}发布于 2013-06-11 22:14:02
您只需公开属性getter,并使用它:
class MyOtherClass
{
public MyOtherClass()
{
myProperty = new int[3, 3];
}
public int[,] myProperty
{
get; private set;
}
}发布于 2013-06-11 22:18:43
除了直接公开数组的其他答案之外,还可以考虑使用索引器
public class MyIndexedProperty
{
private int[,] Data { get; set; }
public MyIndexedProperty()
{
Data = new int[10, 10];
}
public int this[int x, int y] {
get
{
return Data[x, y];
}
set
{
Data[x, y] = value;
}
}
}所以你的课看起来可能是这样的:
public class IndexerClass
{
public MyIndexedProperty IndexProperty { get; set; }
public IndexerClass()
{
IndexProperty = new MyIndexedProperty();
IndexProperty[3, 4] = 12;
}
}注意,您需要确保在访问数据之前对数据进行初始化--我已经在MyIndexedProperty构造函数中这样做了。
在使用中,其结果是:
IndexerClass indexedClass = new IndexerClass();
int someValue = indexedClass.IndexProperty[3, 4]; //returns 12这种方法的主要优点是隐藏了在调用者使用set和get方法时存储值的实际实现。
您还可以在决定继续执行set操作之前检查值。
public int this[int x, int y] {
get
{
return Data[x, y];
}
set
{
if (value > 21) //Only over 21's allowed in here
{
Data[x, y] = value;
}
}
}https://stackoverflow.com/questions/17054683
复制相似问题