【发布时间】:2011-02-07 13:53:46
【问题描述】:
我在列表集合中存储数据时遇到问题。如果我添加新数据,它会重写旧数据,并且列表中仍然只有一项。
这里是main方法,从这个方法中我调用方法OpenChatScreen,它是ChatScreenManager类的方法,是problen的根。
private void OpenTabChatWindow(string nick)
{
try
{
new System.Threading.Tasks.Task(() =>
{
IDetailData oponent = new DetailData();
oponent = Service.DetailData(Account, nick);
Execute.OnUIThread((System.Action)(() =>
{
//here I call problem method OpenChatScreen method where is the problem,
//it use still the same reference on object opponent
if (ChatScreenManager.OpenChatScreen(true, Account, oponent, Account.DetailData.Info.Nick))
{
AddConversationHistory(nick);
}
}));
}
).Start();
}
catch (Exception exception)
{
MsgBox.ShowException(exception);
}
}
ChatScreenManager 类的代码:
public IDictionary<string,object> ActiveChatScreens { get; set; }
or
public IList<string,> ActiveChatScreens { get; set; }
如果我使用字典或列表,问题也是一样的。
public bool OpenChatScreen(bool useTabChat, IAccount account, IDetailData oponent, string avatarNick)
{
if (!ActiveChatScreens.Contains(oponent.Info.Nick))
{
if(useTabChat)
{
//in this method - OpenTabChat is problem
OpenTabChat(account, oponent, avatarNick);
return true;
}
}
return false;
}
private void OpenTabChat(IAccount account, IDetailData oponent, string avatarNick)
{
if (!ChatShellViewModel.IsActive)
{
OpenChatShell();
}
ChatShellViewModel.OpenChatTab(account, oponent, avatarNick);
//here is the root of problem, it use same reference of object opponent
ActiveChatScreens.Add(oponent.Info.Nick);
}
所以我从 DetailData 的方法 OpenTabChatWindow 对象类型传递,并将 som 字符串属性存储在另一个类的 List 中,但在此对象上使用相同的引用并重写列表中的数据。
我尝试创建新的对象:
IDetailData oponent = new DetailData();
oponent = Service.DetailData(Account, nick);
并将这个对象传递给问题方法,但它没有解决它。
【问题讨论】:
-
ActiveChatScreens 是什么数据类型?
-
抱歉,我的错误,我编辑了我的问题。它是列表,也可以是字典。问题是一样的,我将对手.Info.Nick 存储到集合中。但它对对象对手使用相同的引用并重写列表中的项目。
-
如果您在字典中使用相同的引用,它应该覆盖以前的内容。如果您尝试添加新消息,则需要使用 messageid 作为键,并且在它包含的对象中具有谁和什么的属性。是这种情况还是您尝试打开新的聊天窗口,然后为什么它会被覆盖?
-
没有。我使用集合字典或列表来检查带有某个 id 的屏幕是否处于活动状态。我添加了新的对象实例,请参见 OpenTabChat 方法 => IDetailData oponent = new DetailData();,对象 opponet 具有字符串属性 Nick,Nick 是字典中的键。所以我添加键对值 Tom, object 然后 Mike, object 并且这个重写了 Tom,object 在字典中。因为这个动作在字典里只有一对 Mike, object。我知道我的英语很糟糕,你现在明白我了吗?
标签: c# list collections reference generics