【发布时间】:2017-09-19 08:18:20
【问题描述】:
我想创建一个映射,其中属性对象的名称作为键,类型对象的列表作为值。
就我而言,我想要一张地图:
Dictionary<string, List<Object1 Or 2>> objectToListofObj1Or2 = new Dictionary<string, List<Object1 Or 2>>();
我可以有一个联系人或地址列表。
我有一个方法来初始化我的地图,现在它是 AbstractEntity,Adress 和 Contact 的超类:
public Dictionary<string, List<AbstractEntity>> InitializeMapping()
{
Dictionary<string, List<AbstractEntity>> objectToListContactCorrespondance1 = new Dictionary<string, List<AbstractEntity>>();
objectToListContactCorrespondance1["CodeContactFactAchatExterne"] = ContactsFacturationAchatExterne.Cast<AbstractEntity>().ToList();
//my key is the property name, value is my list already created, here is a List of type Contact
objectToListContactCorrespondance1["CodeContactContractAchatExterne"] = ContactsContractualisationAchatExterne.Cast<AbstractEntity>().ToList();
//here a list of type Adress
objectToListContactCorrespondance1["CodeAdresseContractAchatExterne"] = AdressesContractualisationAchatExterne.Cast<AbstractEntity>().ToList();
我这样做是为了在视图中的列表中预先选择很多具有相应 CodeAdress 或 CodeContact 的 rambaComboBox,如下所示:
Dictionary<string, List<AbstractEntity>> mapping = InitializeMappingContact();
foreach (PropertyInfo propertyInfo in dataInit.GetType().GetProperties())
{
if (mapping.ContainsKey(propertyInfo.Name) && (alreadyIn.Where(code => code == propertyInfo.Name).ToList().Count == 0))
{
if (mapping[propertyInfo.Name].First().GetType() == typeof(Contact))
{
Contact test = (Contact)mapping[propertyInfo.Name].First();
propertyInfo.SetValue(dataInit, mapping[propertyInfo.Name].Count == 1 ? test.CodeContact : null, null);
}
else
{
Adresse test = (Adresse)mappingContact[propertyInfo.Name].First();
propertyInfo.SetValue(dataInit, mappingContact[propertyInfo.Name].Count == 1 ? test.CodeAdresse : null, null);
}
}
}
我的地图现在可以工作了,我添加了 FIRST()。但是我的组合框不是用这一行选择的(dataInit 允许我初始化视图):
propertyInfo.SetValue(dataInit, mappingContact[propertyInfo.Name].Count == 1 ? test.CodeContact : null, null);
否则,如果我不使用我的 foreach 和 Initialize 方法,我必须像这样手动逐行执行:
dataInit.CodeAdresseContractAchatSVD = AdressesContractualisationAchatSVD.Count == 1 ? AdressesContractualisationAchatSVD.First().CodeAdresse : null;
我想做:
dataInit."mapping[propertyInfo.Name]" = mappingContact[propertyInfo.Name].Count == 1 ? (Adress)mappingContact[propertyInfo.Name].First().CodeAdresse : null;
【问题讨论】:
-
请注意,
mapping[propertyInfo.Name].GetType() == typeof(Contact)最好写成mapping[propertyInfo.Name] is Contact -
为什么使用 AbstractEntity 不起作用?调试代码时会发生什么?
-
我可能发现了什么:我的测试类型错误,我需要做:mapping[propertyInfo.Name].FIRST().GetType() == typeof(Contact) 或列出作为对应类型
-
我已经更新了我的帖子
标签: c# wpf dictionary generics types