要给出通过的方法,用于Object对象转换成Dictionary<string,object>字典对象,key为字段名称,value为字段的值,给出c#代码
时间: 2024-03-19 10:43:09 浏览: 59
C# 参数按照ASCII码从小到大排序(字典序)
可以使用反射来实现Object对象转换成Dictionary<string, object>字典对象,具体代码如下:
```csharp
using System;
using System.Collections.Generic;
using System.Reflection;
public static class ObjectExtensions
{
public static Dictionary<string, object> ToDictionary(this object obj)
{
var dict = new Dictionary<string, object>();
if (obj == null) return dict;
var type = obj.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var propertyName = property.Name;
var propertyValue = property.GetValue(obj, null);
dict[propertyName] = propertyValue;
}
return dict;
}
}
```
使用示例:
```csharp
var person = new { Name = "Tom", Age = 18 };
var dict = person.ToDictionary();
foreach (var item in dict)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
```
输出结果:
```
Name: Tom
Age: 18
```
阅读全文