【问题标题】:C# reflection dictionaryC# 反射字典
【发布时间】:2013-07-07 18:20:54
【问题描述】:

说我有这个代码:

Dictionary<String, String> myDictionary = new Dictionary<String, String>();
Type[] arguments = myDictionary.GetType().GetGenericArguments();

在我的程序中,myDictionary 属于未知类型(它是从反序列化的 XML 返回的对象),但就本问题而言,它们是字符串。我想创建这样的东西:

Dictionary<arguments[0],arguments[1]> mySecondDictionary = new Dictionary<arguments[0],arguments[1]>();

显然,它不起作用。 我在 MSDN 上搜索,我看到他们正在使用 Activator 类,但我不明白。 也许更高级的人可以帮助我一点。

【问题讨论】:

  • 请给您的问题一个有意义的标题。不要只列出标签。这毫无意义,也不会吸引用户调查并尝试帮助您。
  • 只是对您最近删除的问题的注释。 Everything has been invented

标签: c# serialization reflection dictionary


【解决方案1】:

这种方法存在问题。 我会尽力解释。 我编写了一个程序,它首先将一个类序列化为 XML,然后将其反序列化。 基本上,它是一个通用类,它包含一个 List(与该类相同的类型)。 因此,类的类型可以是任何类型,从简单类型(如 string、int 等)到更复杂的类(如书类或人)。使用 XmlSerializer.Deserialize 方法并获取对象后,我应该使用反射来重建对象并访问列表。而我不能那样做。 所以,如果我有类似的东西:

Type classToCreate = typeof(classToBeSerialized<>).MakeGenericType(arguments);
var reconstructedClass = Activator.CreateInstance(classToCreate);

classToBeSerialized 是假定的类(它有我说过的列表),returnObject 是从 XmlSerializer.Deserialize 返回的对象,我想像这样访问列表:

 ((reconstructedClass)returnedObject).lista

基本上,我使用反射将对象投射到它的源。

【讨论】:

    【解决方案2】:

    您可以使用您提到的激活器类来从给定类型创建对象。 MakeGenericType 方法允许你指定一个类型数组作为泛型对象的参数,这是你试图模拟的。

    Dictionary<String, String> myDictionary = new Dictionary<String, String>();
    Type[] arguments = myDictionary.GetType().GetGenericArguments();
    
    Type dictToCreate = typeof(Dictionary<,>).MakeGenericType(arguments);
    var mySecondDictionary = Activator.CreateInstance(dictToCreate);
    

    上面的代码基本上没有意义,因为您事先知道字典是String,String,但假设您有办法在运行时检测到其他地方所需的类型,您可以使用最后两行来实例化该类型的字典。

    【讨论】:

      【解决方案3】:

      我知道这是一个旧线程,但我只是需要类似的东西,并决定展示它,(你知道谷歌)。

      这基本上是@user2536272 对答案的重写

      public object ConstructDictionary(Type KeyType, Type ValueType)
      {
          Type[] TemplateTypes = new Type[]{KeyType, ValueType};
          Type DictionaryType = typeof(Dictionary<,>).MakeGenericType(TemplateTypes);
      
          return Activator.CreateInstance(DictionaryType);
      }
      
      public void AddToDictionary(object DictionaryObject, object KeyObject, object ValueObject )
      {
          Type DictionaryType = DictionaryObject.GetType();
      
          if (!(DictionaryType .IsGenericType && DictionaryType .GetGenericTypeDefinition() == typeof(Dictionary<,>)))
              throw new Exception("sorry object is not a dictionary");
      
          Type[] TemplateTypes = DictionaryType.GetGenericArguments();
          var add = DictionaryType.GetMethod("Add", new[] { TemplateTypes[0], TemplateTypes[1] });
          add.Invoke(DictionaryObject, new object[] { KeyObject, ValueObject });
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-03
        • 1970-01-01
        • 2023-04-09
        • 2013-08-19
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        • 2018-11-17
        • 2013-09-23
        相关资源
        最近更新 更多