我有多个具有相似属性的对象。对象存储在字典中。现在,我希望一种方法可以与所有词典一起使用。
我尝试使它们成为另一个对象的子元素。使用父对象作为参数并对其子对象调用函数对我不起作用。
ArticleItem.cs
:
public class ArticleItem
{
public int ID { get; set; }
public string Text { get; set; }
... constructor and so on...
}
ArticleItemB.cs
:
public class ArticleItemB
{
public int ID { get; set; }
public string Text { get; set; }
public string AnotherText { get; set; }
... constructor and so on...
}
Programm.cs
:
public Dictionary<string, ArticleItem> newArticle_Catalog = new
Dictionary<string, ArticleItem>();
public Dictionary<string, ArticleItemB> newArticleB_Catalog = new
Dictionary<string, ArticleItemB>();
newArticle_Catalog.Add("1", new ArticleItem(1,"ABC"));
newArticle_Catalog.Add("2", new ArticleItem(2,"DEF"));
newArticleB_Catalog.Add("1", new ArticleItemB(1,"ABC","DEF"));
newArticleB_Catalog.Add("2", new ArticleItemB(2,"GHI","JKL"));
public void PrintCatalog(Dictionary<string, OBJECTTYPE> catalog)
{
foreach (var item in newCatalog)
{
Console.WriteLine(item.value.ToString());
}
}
我想打PrintCatalog()
,就像:
PrintCatalog(newArticle_Catalog);
或类似的
PrintCatalog(newArticleB_Catalog);
并打印出他们的.ToString()
答案 0 :(得分:3)
创建一个通用的基类为:
public abstract class ArticleItemBase
{ }
并让您的类从其继承为:
public class ArticleItem : ArticleItemBase
和
public class ArticleItemB : ArticleItemBase
然后,您可以让PrintCatalog
接受具有通用值类型的Dictionary,并将其限制为仅属于基类的对象:
public static void PrintCatalog<T>(Dictionary<string, T> catalog) where T : ArticleItemBase
{
foreach (var item in catalog)
{
Console.WriteLine(item.Value.ToString());
}
}
答案 1 :(得分:2)
创建具有这些属性的基类,并从所有Item类继承该基类。 然后在PrintCatalog中只需采用基类类型的参数,而不是每个项目