【问题标题】:How can I get the types in Dictionary<int, string>?如何获取 Dictionary<int, string> 中的类型?
【发布时间】:2014-08-04 06:54:54
【问题描述】:

要求是这样的。现在我有了字典。

Dictionary<int,string> dic = new Dictionary<int,string>();
//... some other operations
Type t = typeof(Dictionary<int,string>);

现在我想获取类型 int 和 string。我怎样才能得到这两个?非常感谢。

更新:

感谢您的回复。实际上我的要求是基于从字典类型获得的两种类型创建另一个泛型类。就这样。

PropertyType propertyType = typeof(Dictionary<int,string>);
if (propertyType.Name.Contains("Dictionary"))
{
    Type keyType = propertyType.GetGenericArguments()[0];
    Type valueType = propertyType.GetGenericArguments()[1];
    propertyType = typeof(SerializableDictionary<keyType, valueType>);
}
//And after this, it will dynamically create a class and add the propery as one
//of its properties

现在我不能使用propertyType = typeof(SerializableDictionary&lt;keyType, valueType&gt;)。我应该如何更新此声明?谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:

    这是一个sn-p:

    Type keyType = t.GetGenericArguments()[0];
    Type valueType = t.GetGenericArguments()[1];
    

    更新:

    var typeOfNewDictonary = typeof(SerializableDictionary<,>)
                                   .MakeGenericType(new[] 
                                               { 
                                                   keyType, 
                                                   valueType 
                                               });
    

    顺便说一句: 以下行是错误的:

    PropertyType propertyType = typeof(Dictionary<int,string>);
    

    应该是这样的:

    Type propertyType = typeof(Dictionary<int,string>);
    

    更重要的是,if (propertyType.Name.Contains("Dictionary")) 中的条件毫无意义。它总是被评估为true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2012-11-22
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多