![](/img/trans.png)
[英]Visual C# - Access instance of object created in one class in another
[英]C# How to access a List instance created by another class
这个问题的答案对任何人来说可能都非常明显,但目前我在尝试弄清楚如何访问在以前的 class 中创建的列表时遇到了问题。
这是我目前正在做的事情,这会导致错误“非静态字段、方法或属性‘TestClass.TestList’需要一个 object 引用”。
public partial class TestClass
{
// Make a static list
public static List<string> TestStaticList = new List<string>();
// Make a non-static list - How do I reference this?
public List<string> TestList { get; set; }
// Clear the static list, and add the entries of the non-static list
public static void UpdateList()
{
TestStaticList.Clear();
for (int i = 0; i < TestList.Count; i++)
{
string NewString = TestList[i];
TestStaticList.Add(NewString);
}
}
}
我的问题是如何引用该列表? 值得注意的是,我确实需要它保持非静态。 我四处寻找有关此的信息,但到目前为止我没有找到任何信息,或者我没有注意到它可以解决我的问题,所以如果这是重复的,我很抱歉。 在此先感谢您的帮助。
您看到该错误的原因是您无法在 static 方法中引用非静态属性。
如果不生成TestList
static,最好的办法是将TestList
或TestClass
作为参数传递到UpdateList
中。 例如:
public static void UpdateList(TestClass testClass)
{
TestStaticList.Clear();
for (int i = 0; i < testClass.TestList.Count; i++)
{
string NewString = testClass.TestList[i];
TestStaticList.Add(NewString);
}
}
由于您“需要它保持非静态”,因此您不可能在 static 方法中访问它,因为非静态成员(字段、方法、属性和事件等)“链接”到(或关联)它的实例。 换句话说,那些在不同实例中的可能有不同的值。 在不与任何实例关联的 static 方法中,您当然不能要求编译器访问非静态成员,因为它不知道该成员与哪个实例关联。 您可以使用“A.TestList”指定实例。 如果您希望该方法访问每个实例,您可以维护一个 static 列表并在构造函数中调用 Add(this) 并在析构函数中删除自身并在您的方法中迭代列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.