使用泛型创建新对象

本文关键字:对象 新对象 泛型 创建 | 更新日期: 2023-09-27 18:22:14

对于同一主题上的多个问题如此接近,我感到抱歉,但我是泛型的新手,尽管我觉得它很有趣,但也有点令人困惑。

我需要使用泛型来检索Dictionary中的条目,如果条目不存在,我需要创建它。Dictionary Key是一个String,Value是一个容器类——在这种情况下是PersonObject类型,但它可以是任何类型。多亏了dtb和p.s.w.g,我目前工作得很好,但我需要以某种方式使新对象的创建变得通用。

IDictionary list = source.GetType().GetProperty(dictionaryName).GetValue(source, null) as IDictionary;
if (!list.Contains(property))
    list.Add(property, new HobbyObject());

我想创建一个由我正在访问的Dictionary定义的类型的新对象,而不是new HobbyObject()。这甚至可以通过反思来完成吗?还是我只需要为所有可能传入的字典写一个大的Switch Case?

感谢您的帮助。

使用泛型创建新对象

使用Activator.CreateInstance

list.Add(property, Activator.CreateInstance(source.GetType());

感谢大家的帮助。我在这里找到了解决方案,这让我走了很长的路。

对于那些有同样问题的人,我修改了代码,使其显示为:

IDictionary list = source.GetType().GetProperty(dictionaryName).GetValue(source, null) as IDictionary;
if (!list.Contains(property))
{
    Type[] arguments = list.GetType().GetGenericArguments();
    list.Add(property, Activator.CreateInstance(arguments[1]));
}

GetGenericArguments()为我提供了字典的参数类型。