![](/img/trans.png)
[英]How can I transform a List <string> to a Dictionary<string, int>?
[英]How can I get the types in Dictionary<int, string>?
要求是这样的。 现在我有字典。
Dictionary<int,string> dic = new Dictionary<int,string>();
//... some other operations
Type t = typeof(Dictionary<int,string>);
现在,我要获取类型int和字符串。 我怎么能得到两个? 非常感谢你。
更新:
感谢您的答复。 实际上,我的要求是基于这两种类型创建另一个通用类,它们是从字典类型中获得的。 像这样。
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<keyType, valueType>)
。 我应该如何更新此声明? 谢谢。
这是一个片段:
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.