我在更新集合中的对象时遇到问题。我有以下课程结构:
class XYZ
{
public static ObservableCollection<CustomObject> List =
new ObservableCollection<CustomObject>();
public void OnOpen()
{
}
public void OnMessage()
{
}
}
在OnOpen()
方法中,我想将对象添加到列表中。有没有办法保持对这个确切对象的引用,所以我总是可以更新其属性而无需查看整个列表?
我想在将它添加到列表之前将其保存在本地属性中,如下所示:
private CustomObject obj;
//OnOpen
obj = new CustomObject();
List.Add(obj);
但那并没有奏效。然后我尝试将其添加为指针,但Visual Studio表示它无法从托管类型CustomObject
创建指针。
如果没有先通过List
重复查找对象,如何获取对象的引用?
答案 0 :(得分:1)
有点不清楚你想要实现的目标。如果您需要保持对对象的引用,只需声明一个变量并保留它。保留变量的位置取决于您尚未共享的要求。例如:
class XYZ
{
private CustomObject theObjectINeedAReferenceTo;
public static ObservableCollection<CustomObject> List =
new ObservableCollection<CustomObject>();
public void OnOpen()
{
theObjectINeedAReferenceTo = new CustomObject();
List.Add(theObjectINeedAReferenceTo);
...
}
public void OnMessage()
{
...
}
}
中的任何,您现在可以访问您的对象。调用方法OnOpen()
后,可以进行访问。此外,每次调用OnOpen()
时引用都会更改。上面的例子不是线程安全的。
答案 1 :(得分:0)
您的原始方法是正确的。快速工作的例子,展示你如何做到这一点。点击最佳做法,避免混淆答案,如果你可以帮助它试图避免静态引用。
public class CustomObject
{
}
public class CustomObjectList
{
public static ObservableCollection<CustomObject> List = new ObservableCollection<CustomObject>();
// Instance property
public CustomObject NonStaticCustomObject { get; set; }
// Static property
public static CustomObject StaticCustomObject { get; set; }
public void OnOpen()
{
// This is a reference of the new object added to the collection scoped to the method.
var newCustomObject = new CustomObject();
// Add it to the list
List.Add(newCustomObject);
// Store as a static reference
CustomObjectList.StaticCustomObject = newCustomObject;
// Store as an instance reference
NonStaticCustomObject = newCustomObject;
}
public void OnClose()
{
}
}
public class SomeOtherClass
{
public void UseList()
{
var customList = new CustomObjectList();
customList.OnOpen();
// We can get access to the static reference like this.
var itemFromStatic = CustomObjectList.StaticCustomObject;
// We can get access to the non static reference like this.
var itemFromInstance = customList.NonStaticCustomObject;
}
}