如何从父类中检索值 [英] How do I retrieve a value from a parent class
问题描述
有人可以告诉我以下的最佳解决方案
有没有办法从父类中检索一个值,如下所示...
Can somebody please tell me the best solution to the following
Is there a way to retrieve a value from a parent class such as the following...
public class MyGrid
{
public List<Column> Columns = new List<Column>();
private int DefaultColumnWidth = 64;
}
public class Column
{
public Column()
{
Width = -1;
}
public int Width
{
get
{
if (Width >= 0)
return Width;
else
// return DefaultColumnWidth from parent class
return base.DefaultColumnWidth;
}
set;
}
}
我想要它,这样如果DefaultColumnWidth改变,那么列将反映这一变化。
是...的最佳解决方案
将DefaultColumnWidth作为参考传递
以某种方式将父类引用到变量中
获取列类以返回它具有的值,并获取父类以检查它是否小于零,如果为true,则使用DefaultColumnWidth
花了几个小时阅读这个,但不确定哪条路是最好的(甚至可能)
谢谢。
I want it so that if the DefaultColumnWidth changes, then the columns will reflect the change.
Is the best solution to...
Pass the DefaultColumnWidth as a reference
Somehow reference the parent class into a variable
Get the column class to return what value it has, and get the parent class to check if it is less than zero, and if true, use the DefaultColumnWidth
Spent hours reading about this, but not sure which path is the best (or even possible)
Thank you.
推荐答案
public class MyGrid
{
public List<Column> Columns = new List<Column>();
public int DefaultColumnWidth
{
get
{
return _DefaultColWid;
}
set
{
if (value != _DefaultColWid)
{
_DefaultColWid = value;
List<Column> col = new List<Column>();
foreach (var item in Columns)
{
item.Width = value;
col.Add(item);
}
Columns = col;
}
}
}
private int _DefaultColWid = 10;
public void Test()
{
Columns.Add(new Column());
int x;
x = Columns[0].Width;
Console.WriteLine(x);
DefaultColumnWidth = 121;
x = Columns[0].Width;
Console.WriteLine(x);
DefaultColumnWidth = 45;
x = Columns[0].Width;
Console.WriteLine(x);
}
}
public class Column : MyGrid
{
private int width = -1;
public int Width
{
get
{
if (width >= 0)
return width;
else
return base.DefaultColumnWidth;
}
set
{
width = value;
}
}
}
这就是我所做的,但这不是正确的方法。你的场景
你需要实现一个名为OBSERVER的设计模式,这里是它的链接。
http://www.dofactory.com/Patterns/PatternObserver.aspx#_self1 [ ^ ]
首先从Mygrid类继承Column类,第二个使变量public.then你得到的值。
Firstly inherit Column class from Mygrid class and second make that variable public.then you get the value.
public class MyGrid
{
public List<Column> Columns = new List<Column>();
public int DefaultColumnWidth = 64;
}
public class Column:MyGrid
{
public Column()
{
Width = -1;
}
public int Width
{
get
{
if (Width >= 0)
return Width;
else
// return DefaultColumnWidth from parent class
return DefaultColumnWidth;
}
set;
}
}
这篇关于如何从父类中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!