假设我有以下情况:
public class Foo
{
protected List<String> FooList = new List<string>();
public void OperationsOnFoo()
{
//Some stuff who's going to add data to FooList
}
}
public class Foo2 : Foo
{
public void Foo2Methods()
{
//I can access FooList but i can't get its data
}
}
}
表格部分......
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Select Files
private void button1_Click(object sender, EventArgs e)
{
var InstanceOfFoo2 = new Foo2();
InstanceOfFoo2.Foo2Methods();
}
我可以使用Foo中的所有变量和方法;但我无法访问存储在他们身上的数据。 有没有办法做到这一点(而不是设置公开),或者我应该将内容传递给public var并在子类上使用它?
由于
答案 0 :(得分:1)
我假设你想要保护他们免于设置,而不是读取,因为你显然需要阅读这些值。请尝试以下方法:
public class Foo
{
public List<String> FooList { get; private set; }
public Foo()
{
FooList = new List<string>();
}
public void OperationsOnFoo()
{
//Some stuff who's going to add data to FooList
}
}
public class Foo2 : Foo
{
public void Foo2Methods()
{
//Have fun getting the data here!
}
}
编辑:
这是一个有效的计划。它显示项目数和列表中的每个项目:
namespace ConsoleSandbox
{
class Program
{
static void Main(string[] args)
{
var foo = new Foo2();
foo.OperationsOnFoo();
foo.Foo2Methods();
Console.ReadLine();
}
}
public class Foo
{
public List<String> FooList { get; private set; }
public Foo()
{
FooList = new List<string>();
}
public void OperationsOnFoo()
{
for (int i = 0; i < 100; i++)
{
FooList.Add(i.ToString());
}
}
}
public class Foo2 : Foo
{
public void Foo2Methods()
{
Console.WriteLine(FooList.Count);
foreach (var aString in FooList)
{
Console.WriteLine(aString);
}
}
}
}