【问题标题】:C# get the types defining a Dictionary at run timeC# 在运行时获取定义字典的类型
【发布时间】:2010-11-02 05:09:52
【问题描述】:

我想知道在运行时获取定义字典的通用参数的最佳方法是什么。

举个例子:

Dictionary<string, object> dict;

如何在运行时发现键是字符串?

【问题讨论】:

    标签: c# .net generics types type-parameter


    【解决方案1】:

    这是一个 NUnit 测试来演示 Mehrdad 的答案,并使用包含整数作为键和字符串作为值的字典:

            [Test]
            public void testGetPhysicalTypeForGenericDictionary()
            {
                IDictionary<int, string> myDictionary = new Dictionary<int, string>();
                Type [] myTypes = myDictionary.GetType().GetGenericArguments();
                Assert.AreEqual(2, myTypes.Length);
                var varTypes = myDictionary.GetType().GetGenericArguments();
                Assert.AreEqual("Int32", varTypes[0].Name);
                Assert.AreEqual("System.Int32", varTypes[0].FullName);
    
                Assert.AreEqual("String", varTypes[1].Name);
                Assert.AreEqual("System.String", varTypes[1].FullName);
            }
    

    【讨论】:

      【解决方案2】:

      我不确定我是否正确理解了您的问题,但我认为您的意思是这样的:

      Dictionary<string, object> dict = new Dictionary<string, object>();
      // ...
      var args = dict.GetType().GetGenericArguments();
      // args[0] will be typeof(string)
      

      【讨论】:

      • 干杯,你确实理解我的问题,第一次写得不好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 2022-11-10
      相关资源
      最近更新 更多