c# Dictionary反射获取Keys
时间: 2023-12-20 13:55:15 浏览: 51
可以通过反射获取C# Dictionary的Keys,具体步骤如下:
1. 获取Dictionary的类型信息:
```
Type dictionaryType = dictionary.GetType();
```
2. 获取Dictionary的Keys属性信息:
```
PropertyInfo keysProperty = dictionaryType.GetProperty("Keys");
```
3. 获取Keys属性的值:
```
IEnumerable keys = (IEnumerable)keysProperty.GetValue(dictionary);
```
4. 遍历Keys的值:
```
foreach (var key in keys)
{
// do something with key
}
```
完整代码示例:
```
Dictionary<string, int> dictionary = new Dictionary<string, int>()
{
{ "apple", 1 },
{ "banana", 2 },
{ "orange", 3 }
};
Type dictionaryType = dictionary.GetType();
PropertyInfo keysProperty = dictionaryType.GetProperty("Keys");
IEnumerable keys = (IEnumerable)keysProperty.GetValue(dictionary);
foreach (var key in keys)
{
Console.WriteLine(key);
}
```
输出结果:
```
apple
banana
orange
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)